我如何改变UIButton标题颜色?

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

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

如何更改标题颜色?

183707 次浏览

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

例子:

objective - c

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

斯威夫特2

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

斯威夫特3

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

感谢richardchildan

你创建的UIButton是添加了ViewController,下面的实例方法改变了UIFonttintColorTextColorUIButton

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 5中,UIButton有一个setTitleColor(_:for:)方法。setTitleColor(_:for:)有以下声明:

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

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

下面的Playground示例代码展示了如何在UIViewController中创建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: UIButton.ButtonType.system)


// Set button's attributes
button.setTitle("Print 0", for: UIControl.State.normal)
button.setTitleColor(UIColor.orange, for: UIControl.State.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: UIControl.Event.touchUpInside)


// Add button to subView
view.addSubview(button)
}


@objc func printZero(_ sender: UIButton) {
print("0")
}


}


let controller = ViewController()
PlaygroundPage.current.liveView = controller

斯威夫特3中的解决方案:

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

这将设置按钮的标题颜色。