UIButton setTitleColor:forState: question

强颜欢笑 提交于 2019-12-17 18:43:29

问题


Why does the following code work...

[signInBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
[signInBtn setTitleColor:[UIColor blackColor] forState:UIControlStateDisabled];

while this does not?

[signInBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted|UIControlStateDisabled];

回答1:


I know this is an old question, but these answers aren't correct.

When you set each separately you are saying the state property should be UIControlStateHighlighted OR UIControlStateDisabled but NOT both

When you bitwise or them together you are stating they must BOTH be set in the state property. Meaning UIControlStateHighlighted AND UIControlStateDisabled are set in the state property.

The example code below perfectly illustrates my point. If you disagree run it for yourself.

[button setTitle:@"highlighted and selected" forState:UIControlStateHighlighted | UIControlStateSelected];
[button setTitle:@"Highlighted only" forState:UIControlStateHighlighted];
[button setTitle:@"Selected only" forState:UIControlStateSelected];
[button setTitle:@"Normal" forState:UIControlStateNormal];

NSLog(@"Normal title: %@", [[button titleLabel] text]); // prints title: Normal

[button setSelected:YES];

NSLog(@"Selected title: %@", [[button titleLabel] text]); // prints title: Selected only 

[button setSelected:NO];
[button setHighlighted:YES];

NSLog(@"highlighted title: %@", [[button titleLabel] text]); // prints title: Highlighted only

[button setSelected:YES];

NSLog(@"highlighted and selected title: %@", [[button titleLabel] text]); // prints title: highlighted and selected



回答2:


Because the setTitleColor:forState: method can only accept a known UIControlState and you're ORing two UIControlState values together.

Each UIControlState is (at a low level) most likely a simple integer constant.

Update:

It's a bitmask, which makes it a rather more odd that it doesn't work, but my point still stands. (It is leaning alarmingly to one side and wobbling dangerously though.)




回答3:


It could be a bug. Try changing bitmask with unexpected value like UIControlStateHighlighted & UIControlStateDisabled, and it make all the state color the same.



来源:https://stackoverflow.com/questions/4370466/uibutton-settitlecolorforstate-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!