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

时间:2014-05-07 04:14:58

标签: ios objective-c cocoa-touch uibutton

我正在尝试以编程方式创建UIButton。但是默认情况下它会变为白色(这是我导航栏的默认颜色,我觉得这是相关的)。我希望它只是Apple7在iOS7中的默认蓝色。我已经设法改变它的默认状态的颜色,但是当我选择它时,文本再次变为白色。我无法弄清楚如何保持蓝色。

有人可以向我解释一下如何以编程方式创建UIButton并使其行为与我在故事板中创建它一样吗?

当前代码:

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

谢谢。

6 个答案:

答案 0 :(得分:28)

试试这段代码:

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

答案 1 :(得分:3)

刚试过

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

有关详细信息,请参阅official documentation of UIButton.

答案 2 :(得分:1)

你试过这个吗?

[cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];

答案 3 :(得分:1)

这将解决您的问题,

    [cancelButton setTitleColor:YOUR COLOR forState:SPECIFIED STATE];

州的价值观是:

UIControlStateNormal
UIControlStateHighlighted                
UIControlStateDisabled    
UIControlStateSelected 

答案 4 :(得分:0)

尝试使用

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

用于指定所有必需状态的颜色。

答案 5 :(得分:0)

夫特:

let button = UIButton (type: UIButtonType.system)

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