0

I have four buttons with tag "1", "2", "3" and "4" . I want to change the title of all buttons when i will click any one of the button. my code is -

@IBAction func answerButtonAction(_ sender: UIButton) {                

    if answerButton.tag == 1 {

    answerButton.setTitle(questionBank.list[questionNumber].answer1, 
    for: .normal)
    } else if answerButton.tag == 2 {

    answerButton.setTitle(questionBank.list[questionNumber].answer2, 
    for: .normal)
    } else if answerButton.tag == 3 {

  answerButton.setTitle(questionBank.list[questionNumber].answer3, 
  for: .normal)
    } else {

  answerButton.setTitle(questionBank.list[questionNumber].answer4, 
  for: .normal)   
    }
}

But my code is not working

Manas Nayak
  • 143
  • 7

2 Answers2

2

You can create your @IBOutlet collection, for example:

@IBOutlet private var buttons: [UIButton]!

Then in your function:

@IBAction func answerButtonAction(_ sender: UIButton) {  

    let answers = [que.answer1, que.answer2, ...]

    zip(buttons, answers).forEach { (button, answer) in
        button.setTitle(answer, for: .normal)
    }              
}
Francesco Deliro
  • 3,899
  • 2
  • 19
  • 24
-1

//Setting UIButton title

let button = UIButton()

button.setTitle("My Amazing Button", for: .normal)

Please try this.

A similar thread is here too,Hope this will help:

Changing text of UIButton programmatically swift

  • You can format your code using: https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks. This helps others reading your answer. – NOhs Jul 05 '19 at 07:49