我怎样才能改变UIButton的标题颜色?

我以编程方式创build一个button……….

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

我怎样才能改变标题颜色?

你可以使用-[UIButton setTitleColor:forState:]来做到这一点。

例:

Objective-C的

 [buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 

Swift 2

 buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal) 

Swift 3

 buttonName.setTitleColor(UIColor.white, for: .normal) 

感谢richardchildan

你创build的UIButton是添加了ViewController,下面的实例方法改变了UIBontton,tintColor和TextColor的UIButton

Objective-C的

  buttonName.titleLabel.font = [UIFont fontWithName:@"LuzSans-Book" size:15]; buttonName.tintColor = [UIColor purpleColor]; [buttonName setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal]; 

迅速

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

Swift3

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

如果你正在使用Swift,这将会做同样的事情:

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

希望有所帮助!

用Swift 3, UIButton有一个setTitleColor(_:for:)方法。 setTitleColor(_:for:)具有以下声明:

 func setTitleColor(_ color: UIColor?, for state: UIControlState) 

设置用于指定状态的标题的颜色。


下面的游乐场代码显示了如何在UIViewController创build一个UIbutton ,并使用setTitleColor(_:for:)更改它的标题颜色:

 import UIKit import PlaygroundSupport class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white // Create button let button = UIButton(type: UIButtonType.system) // Set button's attributes button.setTitle("Print 0", for: UIControlState.normal) button.setTitleColor(UIColor.orange, for: UIControlState.normal) // Set button's frame button.frame.origin = CGPoint(x: 100, y: 100) button.sizeToFit() // Add action to button button.addTarget(self, action: #selector(printZero(_:)), for: UIControlEvents.touchUpInside) // Add button to subView view.addSubview(button) } func printZero(_ sender: UIButton) { print("0") } } let controller = ViewController() PlaygroundPage.current.liveView = controller 

在Playground中selectShow the Assistant Editor > Timeline <Name of the page>.xcplaygroundpage以显示UIViewController创build的实例。

Swift 3中的 解决scheme

 button.setTitleColor(UIColor.red, for: .normal) 

这将设置button的标题颜色。