根据状态编程更改UIButton字体颜色

11

我正在尝试以编程方式创建一个UIButton。 但是,默认情况下它变成了白色(这是我的导航栏的默认颜色,我觉得这很相关)。 我希望它只是在iOS7中的Apple默认蓝色。 我已经成功更改了其默认状态的颜色,但是一旦我选择它,文本又变成了白色。 我找不到如何保持它为蓝色的方法。

请问有人能够向我解释如何以编程方式创建一个UIButton并使其表现得与我在storyboard中创建的一样吗?

目前的代码:

UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
cancelButton.frame = CGRectMake(320 - 150, 0, 140, 40);
[cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
cancelButton.titleLabel.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
cancelButton.titleLabel.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];

谢谢。


设置titleLabel从来没有对我起作用过。@SunnyShah是正确的方法。 - Milo
6个回答

30

尝试这段代码:

UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[cancelButton setFrame:CGRectMake(320 - 150, 0, 140, 40)];
[cancelButton setBackgroundColor:[UIColor clearColor]];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted]; // This will helps you during click time title color will be blue color
[cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
[cancelButton addTarget:self action:@selector(button_Action) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:cancelButton];

虽然你不是第一个回答的,但这个回答是最详细的。谢谢。 - Ian

3

刚刚尝试了一下

[cancelButton setTitleColor:[UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0/255.0 alpha:1.0] forState:UIControlStateNormal];

了解更多信息,请阅读UIButton官方文档


蓝色应该是 -> 蓝色:1.0f,而不是蓝色:1.0/255.o - Kevin

1
你尝试过这个吗?
[cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];

1
这将解决您的问题。
    [cancelButton setTitleColor:YOUR COLOR forState:SPECIFIED STATE];

状态值为:

UIControlStateNormal
UIControlStateHighlighted                
UIControlStateDisabled    
UIControlStateSelected 

0

尝试使用

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state

来指定所有所需状态的颜色。


我明白了,那个方法可行。我以为titleLabel会包含所有的内容,显然我错了。谢谢你。 - Ian
1
不客气。titleLabel 不能用的原因是它只引用了 UIButton 的当前标题属性(而不是所有状态下的标题),就像文档所指定的那样:https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/instp/UIButton/titleLabel。 - Aloha Silver

0

Swift:

let button = UIButton (type: UIButtonType.system)

这将创建一个按钮,使用标准的色调颜色,就像在界面构建器中添加的按钮一样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接