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

Ian*_*Ian 10 cocoa-touch objective-c uibutton ios

我正在尝试以编程方式创建一个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];
Run Code Online (Sandbox Code Playgroud)

谢谢.

Min*_*xel 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];
Run Code Online (Sandbox Code Playgroud)