iOS Xcode:UIButton titleLabel 颜色不断变化

Posted

技术标签:

【中文标题】iOS Xcode:UIButton titleLabel 颜色不断变化【英文标题】:iOS Xcode: UIButton titleLabel color keeps changing 【发布时间】:2014-07-01 20:15:05 【问题描述】:

场景 = 我有一个 UIButton,上面有一个 titleLable(文本),它的特性会根据布尔值是 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

【问题讨论】:

你能发布一些你迄今为止尝试过的代码吗?当我们不知道您尝试了什么时,很难告诉您出了什么问题…… button.titleLable.textColor = [UIColor redColor]; --- 它变为红色,但在启动应用程序并按下按钮时,按钮会在触摸时变回白色。 我的意思是一些代码,比如:你在哪里改变布尔值?你在哪里检查布尔值?你在哪里设置颜色?等 【参考方案1】:

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

试试

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

【讨论】:

【参考方案2】:

你可以用这个:-

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

【讨论】:

【参考方案3】:

斯威夫特 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];

【讨论】:

以上是关于iOS Xcode:UIButton titleLabel 颜色不断变化的主要内容,如果未能解决你的问题,请参考以下文章

IOS UIButton 目标不起作用

IOS开发之XCode学习003:UIButton基础

如何使用 Storyboard 在 Xcode6 中创建 UIButton 连接?

将 UIButton 的 titleLabel 文本与自动布局匹配在固定的恒定宽度上

iOS:禁用时的 UIButton 标题颜色

Xcode11 - UIButton 等控件高度为 48,仅在 XR/XSMAX 设备中的 AppDelegate 中