簡體   English   中英

如何更改 UIButton 標題顏色?

[英]How can I change UIButton title color?

我以編程方式創建一個按鈕............

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 ,以下實例方法更改UIButtonUIFonttintColorTextColor

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)

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM