简体   繁体   English

UIButton 标题文字变色

[英]UIButton title text color change

I have a UIButton in a custom UIView. In the view, I have a function setDisabled:(BOOL)disabled which is called when I want to change the appearance of the UIView.我在自定义 UIView 中有一个 UIButton。在视图中,我有一个 function setDisabled:(BOOL)disabled当我想更改 UIView 的外观时调用它。

\\ Method 1
- (void) setDisabled:(BOOL)disabled
{
   myUIButton.titleLabel.textColor = disabled ? [UIColor systemGrayColor] : [UIColor systemBlueColor];
}
\\ Method 2
- (void) setDisabled:(BOOL)disabled
{
   [myUIButton setTitleColor: disabled ? [UIColor systemGrayColor] : [UIColor systemBlueColor] forState: UIControlStateNormal];
}

I have used this UIView for cells in UITable view.我已经将这个 UIView 用于 UITable 视图中的单元格。 Using Method 1 , the change is not immediately reflected (reflected when i scroll through UITableView) whereas using Method 2 , the color change is immediately reflected.使用方法 1 ,更改不会立即反映出来(当我滚动 UITableView 时反映出来),而使用方法 2 ,颜色变化会立即反映出来。 In this apple documentation, it is mentioned to not use Method 1 .苹果文档中,提到不使用Method 1 However I could not find the reason.但是我找不到原因。 Any leads would be helpful.任何线索都会有所帮助。

Do NOT use "Method 1"...不要使用“方法 1”...

UIKit controls - such as UIButton - have a lot of code that does work "behind the scenes." UIKit 控件——例如UIButton有很多代码在“幕后”工作。

For example, if your button has a normal color of Red, and a Highlighted color of LightGray, and then you execute:例如,如果您的按钮具有红色的正常颜色和 LightGray 的突出显示颜色,然后您执行:

myUIButton.titleLabel.textColor = [UIColor systemBlueColor];

The button itself does not know that you did that.按钮本身并不知道你这样做了。 It still has Red as its normal color property.它的正常颜色属性仍然是红色。

As soon as UIKit updates that button - a tap or a layout change, etc - the text color will be set back to the normal color property.一旦 UIKit 更新该按钮 - 点击或布局更改等 - 文本颜色将设置回正常颜色属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM