melody5417
melody5417

Reputation: 365

Button.titleLabel setTextColor: not working

I write a button and I want to change the text color of the button when i touch it. The code is like:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
[self.titleLabel setTextColor:[UIColor blackColor]];   
}

But it didnt work. Instead, I write

[self setTitleColor:[UIColor greenColor]       forState:UIControlStateNormal];

and it worked. But I dont know the difference. Does anyone know about it, thanks.

Upvotes: 1

Views: 535

Answers (1)

0yeoj
0yeoj

Reputation: 4550

This is quite discussed in the apple UIButton Class Documentation

Although this property is read-only, its own properties are read/write. Use these properties primarily to configure the text of the button. For example:

UIButton *button                  = [UIButton buttonWithType: UIButtonTypeSystem];
button.titleLabel.font            = [UIFont systemFontOfSize: 12];
button.titleLabel.lineBreakMode   = NSLineBreakByTruncatingTail;

Do not use the label object to set the text color or the shadow color. Instead, use the setTitleColor:forState: and setTitleShadowColor:forState: methods of this class to make those changes.

The titleLabel property returns a value even if the button has not been displayed yet. The value of the property is nil for system buttons.

Upvotes: 5

Related Questions