我以编程方式创建一个按钮............
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];
斯威夫特 2
buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
斯威夫特 3
buttonName.setTitleColor(UIColor.white, for: .normal)
您创建的 UIButton
添加了 ViewController
,下面的实例方法来更改 UIButton
的 UIFont
、tintColor
和 TextColor
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)
斯威夫特3
buttonName.titleLabel?.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purple
buttonName.setTitleColor(UIColor.purple, for: .normal)
Swift 3 中的解决方案:
button.setTitleColor(UIColor.red, for: .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
如果您使用的是 Swift,这将执行相同的操作:
buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
希望有帮助!
btn.titleColor
,只有btn setTitleColor
可用