Changing text of UIButton programmatically swift

后端 未结 11 1470
天命终不由人
天命终不由人 2020-11-28 19:34

Simple question here. I have a UIButton, currencySelector, and I want to programmatically change the text. Here\'s what I have:

currencySelector.text = \"foo         


        
相关标签:
11条回答
  • 2020-11-28 19:56

    Swift 5.0

    // Standard State
    myButton.setTitle("Title", for: .normal)
    
    0 讨论(0)
  • 2020-11-28 19:57

    Swift 5:

        let controlStates: Array<UIControl.State> = [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved]
        for controlState in controlStates {
            button.setTitle(NSLocalizedString("Title", comment: ""), for: controlState)
        }
    
    0 讨论(0)
  • 2020-11-28 20:00

    Swift 3

    let button: UIButton = UIButton()
    button.frame = CGRect.init(x: view.frame.width/2, y: view.frame.height/2, width: 100, height: 100)
    button.setTitle(“Title Button”, for: .normal)
    
    0 讨论(0)
  • 2020-11-28 20:04

    Changing title when attributed is a bit different :

    I just ran into a problem : If you have an UIButton with an Attributed Title, you have to use :

    my_btn.setAttributedTitle(NSAttributedString(string: my_title), for: my_state)
    

    as, per Apple SetTitle Doc :

    If you set both a title and an attributed title for the button, the button prefers the use of the attributed title over this one.

    I had an attributed title and I tried to setTitle on it, with no effect...

    0 讨论(0)
  • 2020-11-28 20:12

    To set a title for a button in Xcode using swift - 04: first create a method called setTitle with parameter title and UIController state like below ;

    func setTitle(_ title : String?, for state : UIControl.State)   {
    
    }
    

    and recall this method in your button action method like ;

    yourButtonName.setTitle("String", for: .state)
    
    0 讨论(0)
  • 2020-11-28 20:13

    Swift 3:

    Set button title:

    //for normal state:
    my_btn.setTitle("Button Title", for: .normal)
    
    // For highlighted state:
    my_btn.setTitle("Button Title2", for: .highlighted)
    
    0 讨论(0)
提交回复
热议问题