简体   繁体   中英

iOS Xcode: UIButton titleLabel color keeps changing

Scenario = I have a UIButton with a titleLable (text) on it that's characteristics will change depending upon if a boolean value is YES or NO. I set that button's titleLabel textColor to white in storyboards. Now, programmatically, if the boolean value is set to NO, I would like that color to change to red.

All of this works fine.

Problem = When I tap the button after it has been set to red, upon lifting of my finger, the titleLabel on the button changes back to white.

Question = How can I set the color of my titleLabel to the right color and keep it the correct color throughout the duration of the boolean variable's state?

//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"]];

}

Order of Fubar goes like this...

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

Instead of self.button.titleLabel.text = ...

try

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

您可以使用以下方法:

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

Swift 3

Using System Color

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

Using with RGB Color

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

Objective-c

Using System Color

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

Using with RGB Color

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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