How to set label color and alignment for uibutton dynamically

colors, dynamic, ios, uibutton

Solution

You are setting the color to `titleLabel` instead of this, use:

[toButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

For text alignment this line will work:

toButton.titleLabel.textAlignment = UITextAlignmentRight;

You can also use:

toButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

Problem

I am using the following code to set the title label's text color, alignment and font size when adding a ui button in xcode. The font size is picked up but not the text color and alignment, why? Thanks. ``` toButton.titleLabel.textColor = [UIColor redColor]; toButton.titleLabel.textAlignment = UITextAlignmentRight; toButton.titleLabel.font = [UIFont boldSystemFontOfSize:FONT_SIZE]; [toButton setTitle:fromButton.titleLabel.text forState:UIControlStateNormal]; ```

Original source