Tuesday, March 22, 2011

Objective C/Xcode 4: How to label and internationalize a Round Rect Button (UIButton) programatically

If you only support one language it is easy to go into Interface Builder and set the Label of your Round Rect Button. For localization it is not as easy though.

How to use localization for UILabels

Text Label elements or UILabels can easily be set to a localized String with this command.

@synthesize nameLabel;


self.nameLabel.text = NSLocalizedString(@"name.label.translation", @"Comment for the name label.");

How to NOT use localization for UIButtons

Since buttons have different states the label would disappear if you click it and you only set the title like that.
@synthesize myButton;
self.myButton.titleLabel = = NSLocalizedString(@"button.label.translation", @"Comment for the button label.");

How to USE localization for UIButtons

The proper way is to assign the localized string to all states of the UIButton.

@synthesize myButton;
NSString *buttonLabelString = NSLocalizedString(@"button.label.translation", @"Comment for the button label.");
 [self.myButton setTitle:buttonLabelString forState:UIControlStateNormal];
 [self.myButton setTitle:buttonLabelString forState:UIControlStateHighlighted];
 [self.myButton setTitle:buttonLabelString forState:UIControlStateDisabled];
 [self.myButton setTitle:buttonLabelString forState:UIControlStateSelected];


muguira said...

This is not working for me. I set the property as

@property (nonatomic, assign) IBOutlet UIButton *myButton1;

but the title does not change when I synthesize then call the setTitle method as shown above. It only works if I call the IBAction method for the button and use the sender id like this

[sender setTitle:@"Howdy" forState:UIControlStateNormal];

Could it be that I have set something incorrectly in the Interface Builder? I also tried

UIButton* button = (UIButton *)[self.view viewWithTag:9];
[button setTitle:@"Howdy" forState:UIControlStateNormal];

in the IBAction method of another button. I would like to be able to change the title of this button in another method.

Any suggestions would be greatly appreciated.

stphn said...

Hey muguira,

make sure that you have your label's outlet set to myButton1 in Interface Builder. Then it should work to set the title as described above.

Let me know if that helped.

Post a Comment