How to set the title text color of UIButton?

后端 未结 7 1393
温柔的废话
温柔的废话 2020-12-13 05:18

I tried changing the colors of the text for a button, but it\'s still staying white.

isbeauty = UIButton()
isbeauty.setTitle(\"Buy\", forState: UIControlStat         


        
相关标签:
7条回答
  • func setTitleColor(_ color: UIColor?, 
                   for state: UIControl.State)
    

    Parameters:

    color:
    The color of the title to use for the specified state.

    state:
    The state that uses the specified color. The possible values are described in UIControl.State.

    Sample:

    let MyButton = UIButton()
    MyButton.setTitle("Click Me..!", for: .normal)
    MyButton.setTitleColor(.green, for: .normal)
    
    0 讨论(0)
  • 2020-12-13 05:55

    This is swift 5 compatible answer. If you want to use one of the built-in colours then you can simply use

    button.setTitleColor(.red, for: .normal)
    

    If you want some custom colours, then create an extension for a UIColor as below first.

    import UIKit
    extension UIColor {
        static var themeMoreButton = UIColor.init(red: 53/255, green: 150/255, blue: 36/255, alpha: 1)
    }
    

    Then use it for your button as below.

    button.setTitleColor(UIColor.themeMoreButton, for: .normal)
    

    Tip: You can use this method to store custom colours from rgba colour code and reuse it throughout your application.

    0 讨论(0)
  • 2020-12-13 06:02

    You have to use func setTitleColor(_ color: UIColor?, for state: UIControlState) the same way you set the actual title text. Docs

    isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), for: .normal)
    
    0 讨论(0)
  • 2020-12-13 06:03

    Example in setting button title color

    btnDone.setTitleColor(.black, for: .normal)
    
    0 讨论(0)
  • 2020-12-13 06:05

    referring to radio buttons ,you can also do it with Segmented Control as following:

    step 1: drag a segmented control to your view in the attribute inspector change the title of the two segments ,for example "Male" and "Female"

    step 2: create an outlet & an action for it in the code

    step 3: create a variable for future use to contain choice's data

    in the code do as following:

    @IBOutlet weak var genderSeg: UISegmentedControl!
    
    var genderPick : String = ""
    
    
     @IBAction func segAction(_ sender: Any) {
    
        if genderSeg.selectedSegmentIndex == 0 {
             genderPick = "Male"
            print(genderPick)
        } else if genderSeg.selectedSegmentIndex == 1 {
            genderPick = "Female"
              print(genderPick)
        }
    }
    
    0 讨论(0)
  • 2020-12-13 06:08

    set title color

    btnGere.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
    
    0 讨论(0)
提交回复
热议问题