Button.titleLabel setTextColor: not working

| | August 6, 2015

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.

One Response to “Button.titleLabel setTextColor: not working”

  1. 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.

Leave a Reply