如何更改UIButton标题颜色?

时间:2010-03-19 00:31:09

标签: ios objective-c iphone 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];

如何更改标题颜色?

5 个答案:

答案 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)

感谢richardchildan

答案 1 :(得分:23)

您创建的UIButton已添加ViewController,以下实例方法可更改UIFont的{​​{1}},tintColorTextColor

<强>目标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)

Swift 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)

希望有所帮助!