UIButton文字颜色无法修改的解决方法和知识拓展

时间:2022-12-23 04:53:48

1.普通的按钮中的字更改颜色的方法:

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
 
 
  • 1
  • 1

这段代码将按钮中的文字的颜色,在一般情况下改成黑色。

2.常见错误:

//第一种错误
[customButton.titleLabel setTextColor:[UIColor blackColor]];
//第二种错误
customButton.titleLabel.textColor = [UIColor blackColor];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

通过以上两种方法更改文字颜色无效。 
原因:参考Apple Documentation and API Reference发现 
即titleLabel是readonly,但又由于它继承自UILabel,所以虽然有textcolor的getter和setter方法,但执行无效。 
UIButton文字颜色无法修改的解决方法和知识拓展
同理,buttonName.titleLabel setTextColor等类似的getter和setter方法同样无效(titleLabel is readonly)。如需修改,请直接调用buttonName的对应方法(自行查阅Documentation and API Reference)

3.知识拓展 
button有一个readonly attribute叫currentTitle,继承自NSString其功能等同于button.titleLabel.text。作用是提供了对button.titleLabel.text的快速访问。

4.关于setTitleColor方法中的forState参数: 
此参数表示在某种特定的state下,button会使用给定的title,如果button处于某种特定的state,而开发者没有指定此state下的title,系统会默认调用UIControlStateNormal下的title,如果UIControlStateNormal下也没有设置title,则会默认使用system value。

下面给出一个例子,表现不同的state的不同作用。

//核心代码1:
[presentButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
  • 1
  • 2
  • 1
  • 2

效果: 
UIButton文字颜色无法修改的解决方法和知识拓展

//核心代码2:
[presentButton setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
  • 1
  • 2
  • 1
  • 2

UIButton文字颜色无法修改的解决方法和知识拓展

原理:代码2中,设置presentButton只有在selected的状态下,颜色才会变为橙色,所以点击下一个按钮之后,由于前一个按钮状态变为unselected,所以自然就会变为系统默认的黑色了。免去了多余的若干行代码。