Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change title of UIButton whose title was set in IB as attributed

I have changed titles of UIButtons before using:

- (void)setTitle:(NSString *)title forState:(UIControlState)state

But I've run into a situation where the UIButton I'm using has a mult-line title and will only center the text properly if changed from "plain" to "attributed" in IB. When the title is changed in this way, the usual setTitle: forState: method no longer updates the button.

How do you make changes to an attributed title of a UIButton?

To clarify, so you don't assume I'm just making a stupid mistake, I've used the debugger to peek at the properties of the UIButton and logging the output of

- (NSString *)titleForState:(UIControlState)state

after using

- (void)setTitle:(NSString *)title forState:(UIControlState)state

to set it returns the value just set. Problem is it doesn't change the appearance of the button as long as the title is set to attributed in IB. My code works fine by simply changing this to plain. But this is not a solution as described in the link above.

like image 971
Jeff Lockhart Avatar asked Sep 29 '12 11:09

Jeff Lockhart


2 Answers

Attributed titles are obtained via

- (NSAttributedString *)attributedTitleForState:(UIControlState)state

and set via

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state

Formatting the NSAttributedString object is a bit complicated, but setting it to nil will clear the title and that's what I needed.

like image 84
Jeff Lockhart Avatar answered Nov 12 '22 18:11

Jeff Lockhart


here's one

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Title" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
 [view addSubview:button];

no need to make changes in- (void)setTitle:(NSString *)title

like image 22
Christien Avatar answered Nov 12 '22 17:11

Christien