Changing text of UIButton programmatically swift

后端 未结 11 1471
天命终不由人
天命终不由人 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 20:13

    //for normal state:

    btnSecurite.setTitle("TextHear", for: .normal)
    
    0 讨论(0)
  • 2020-11-28 20:14

    swift 4.2 and above

    using button's IBOutlet

    btnOutlet.setTitle("New Title", for: .normal)
    

    using button's IBAction

    @IBAction func btnAction(_ sender: UIButton) {
      sender.setTitle("New Title", for: .normal)
    }
    
    0 讨论(0)
  • 2020-11-28 20:16

    Swift 3

    When you make the @IBAction:

    @IBAction func btnAction(_ sender: UIButton) {
      sender.setTitle("string goes here", for: .normal)
    }
    

    This sets the sender as UIButton (instead of Any) so it targets the btnAction as a UIButton

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

    In Swift 3, 4, 5:

    button.setTitle("Button Title", for: .normal)
    

    Otherwise:

    button.setTitle("Button Title", forState: UIControlState.Normal)
    

    Also an @IBOutlet has to declared for the button.

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

    Just a clarification for those new to Swift and iOS programming. Below line of code:

    button.setTitle("myTitle", forState: UIControlState.Normal)
    

    only applies to IBOutlets, not IBActions.

    So, if your app is using a button as a function to execute some code, say playing music, and you want to change the title from Play to Pause based on a toggle variable, you need to also create an IBOutlet for that button.

    If you try to use button.setTitle against an IBAction you will get an error. Its obvious once you know it, but for the noobs (we all were) this is a helpful tip.

    0 讨论(0)
提交回复
热议问题