如何更改UIButton标题颜色?

Hel*_*rld 186 iphone objective-c uibutton ios

我以编程方式创建一个按钮..........

button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
Run Code Online (Sandbox Code Playgroud)

如何更改标题颜色?

Ben*_*ieb 507

你可以-[UIButton setTitleColor:forState:]用来做这件事.

例:

Objective-C的

[buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

斯威夫特2

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

buttonName.setTitleColor(UIColor.white, for: .normal)
Run Code Online (Sandbox Code Playgroud)

感谢richardchildan

  • 例如[buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; (38认同)
  • 我不敢相信[UIButton setTitleColor:forState:]有效,但btn.titleColor = [UIColor x]没有.. (3认同)

Anb*_*hik 23

您创建的UIButton添加了ViewController,下面的实例方法来改变UIFont,tintColorTextColorUIButton

Objective-C的

 buttonName.titleLabel.font = [UIFont fontWithName:@"LuzSans-Book" size:15];
 buttonName.tintColor = [UIColor purpleColor];
 [buttonName setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

迅速

buttonName.titleLabel.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purpleColor()
buttonName.setTitleColor(UIColor.purpleColor(), forState: .Normal)
Run Code Online (Sandbox Code Playgroud)

Swift3

buttonName.titleLabel?.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purple
buttonName.setTitleColor(UIColor.purple, for: .normal)
Run Code Online (Sandbox Code Playgroud)

  • 请不要简单地发布代码.提供有关您的代码的一些解释或信息或用法.例如,请参阅[此答案](http://stackoverflow.com/a/16893057/756941). (3认同)