如何动态设置uibutton的标签颜色和对齐方式



在xcode中添加ui按钮时,我使用以下代码来设置标题标签的文本颜色、对齐方式和字体大小。字体大小被选择了,但文本颜色和对齐方式却没有,为什么?谢谢

toButton.titleLabel.textColor = [UIColor redColor];
toButton.titleLabel.textAlignment = UITextAlignmentRight;
toButton.titleLabel.font = [UIFont boldSystemFontOfSize:FONT_SIZE];
[toButton setTitle:fromButton.titleLabel.text forState:UIControlStateNormal];

您将颜色设置为titleLabel,而不是这样,请使用:

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

对于文本对齐,这一行将起作用:

toButton.titleLabel.textAlignment = UITextAlignmentRight;

您也可以使用:

toButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

最新更新