iOS Xcode:UIButton titleLabel颜色不断变化

时间:2014-07-01 20:15:06

标签: ios objective-c xcode uibutton

场景=我有一个带有titleLable(文本)的UIButton,其特征将根据布尔值是YES还是NO而改变。我在故事板中将该按钮的titleLabel textColor设置为白色。现在,以编程方式,如果布尔值设置为NO,我希望该颜色变为红色。

所有这一切都很好。

问题=当我将按钮设置为红色后点击按钮时,按下按钮时,按钮上的titleLabel会将后面的更改为白色。

问题=如何将我的titleLabel的颜色设置为正确的颜色,并在整个布尔变量的状态期间保持正确的颜色?

//CODE
//Button text set to 'white' in storyboard


if ([[NSUserDefaults standardUserDefaults]boolForKey:@"bool"]==YES) {

    self.button.backgroundColor = [UIColor whiteColor];
    self.button.titleLabel.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue"]];

}

else {

    self.button.backgroundColor = [UIColor whiteColor];
    self.button.titleLabel.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"red"]];

}

Fubar的顺序就是这样......

1 drag UIButton onto view controller
2 set UIButton titleLabel textColor to white (storyboards)
3 in view controller .m viewDidLoad I type the code above
4 I run the program on my iPhone
5 press button (bool = NO and textColor is red)
6 (.00000000001 seconds after #5) I lift my finger from the button and the titleLabel textColor changes back to the white color that is set to in storyboard.
7 frustration ensues

3 个答案:

答案 0 :(得分:3)

而不是self.button.titleLabel.text = ...

[self.button setTitleColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"red"]] forState:UIControlStateNormal];

答案 1 :(得分:1)

您可以使用: -

[self.button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; // You can add whatever color you like.

答案 2 :(得分:1)

Swift 3

使用系统颜色

button.setTitleColor(UIColor.red, for: UIControlState.normal)

使用RGB颜色

btnLogin.setTitleColor(UIColor.init(red: (100.0/255.0), green: (150.0/255.0), blue: (200.0/255.0), alpha: 1), for: UIControlState.normal)

目标c

使用系统颜色

[button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];

使用RGB颜色

[button setTitleColor:[UIColor colorWithRed:(100.0/255.0) green:(150.0/255.0) blue:(200.0/255.0) alpha:1] forState:UIControlStateNormal];
}