简体   繁体   English

如何设置子类UIButton的突出显示标题颜色?

[英]How do I set the highlighted title colour of a subclassed UIButton?

I've subclassed UIButton and am trying to set the title colour when the button is highlighted. 我已经将UIButton子类化了,并且在突出显示按钮时尝试设置标题颜色。 The custom button is also on a nib file. 自定义按钮也位于nib文件上。

I have the code: 我有代码:

- (void)layoutSubviews 
{
    [super layoutSubviews];

    self.titleLabel.textColor = [UIColor blueColor];
    [self setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // Offending line

}

However, the view does not load (seemingly goes into an infinite loop and doesn't show) when I have the setTitleColor:forState: line. 但是,当我有setTitleColor:forState:行时,视图不会加载(看似进入无限循环并且不显示)。 Is it supposed to be declared elsewhere? 它应该在其他地方宣布吗? How else do you set the highlighted title colour of a custom UIButton ? 您如何设置自定义UIButton的突出显示标题颜色?

If you want to do this in layoutSubviews, this will avoid the infinite loop you are currently creating: 如果你想在layoutSubviews中这样做,这将避免你当前正在创建的无限循环:

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.state == UIControlStateHighlighted) {
        self.titleLabel.textColor = [UIColor redColor];
    } else {
        self.titleLabel.textColor = [UIColor blueColor];
    }
}

Are you doing anything else with the UIButton subclass? 你在使用UIButton子类做其他事吗? If all you want to do is change the text colour you can use standard UIButton functionality: 如果您只想更改文本颜色,则可以使用标准UIButton功能:

[button setTitleColor:[UIColor redColor] forControlState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forControlState:UIControlStateNormal];

Do this when setting up the button, it doesnt need to happen everytime layoutSubviews is called 在设置按钮时执行此操作,不需要每次调用layoutSubviews时都会发生这种情况

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

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