我以编程方式创建一个按钮..........
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];
如何更改标题颜色?
答案 0 :(得分:491)
您可以使用-[UIButton setTitleColor:forState:]
执行此操作。
示例:
<强>目标C 强>
[buttonName setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
Swift 2
buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
Swift 3
buttonName.setTitleColor(UIColor.white, for: .normal)
答案 1 :(得分:23)
您创建的UIButton
已添加ViewController
,以下实例方法可更改UIFont
的{{1}},tintColor
和TextColor
<强>目标C 强>
UIButton
<强>夫特强>
buttonName.titleLabel.font = [UIFont fontWithName:@"LuzSans-Book" size:15];
buttonName.tintColor = [UIColor purpleColor];
[buttonName setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
<强> Swift3 强>
buttonName.titleLabel.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purpleColor()
buttonName.setTitleColor(UIColor.purpleColor(), forState: .Normal)
答案 2 :(得分:3)
解决方案
button.setTitleColor(UIColor.red, for: .normal)
这将设置按钮的标题颜色。
答案 3 :(得分:1)
使用Swift 5时,UIButton
有一个setTitleColor(_:for:)
方法。 setTitleColor(_:for:)
有以下声明:
设置用于指定状态的标题颜色。
func setTitleColor(_ color: UIColor?, for state: UIControlState)
以下Playground示例代码显示如何在UIbutton
中创建UIViewController
并使用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
答案 4 :(得分:0)
如果您使用的是Swift,也会这样做:
buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)
希望有所帮助!