How can I change UIButton title color?

前端 未结 5 1838
無奈伤痛
無奈伤痛 2020-12-04 09:14

I create a button programmatically..........

button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(aMethod:)
fo         


        
5条回答
  •  庸人自扰
    2020-12-04 09:46

    With Swift 5, UIButton has a setTitleColor(_:for:) method. setTitleColor(_:for:) has the following declaration:

    Sets the color of the title to use for the specified state.

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

    The following Playground sample code show how to create a UIbutton in a UIViewController and change it's title color using 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
    

提交回复
热议问题