Home > other >  UI Button "if" statement in swift
UI Button "if" statement in swift

Time:12-08

when I type the code in, there is an error saying this:

picture of the error: https://i.stack.imgur.com/ixFaM.png

How can I fix it?

 @IBAction func nextQuestionButton(_ sender: Any) {
        if (nextQuestionButton.isSelected == true) {
            
        }

CodePudding user response:

It's a misunderstanding.

nextQuestionButton is not the button, it's an action connected to the button. The button is represented by the sender parameter.

This syntax makes it clearer

@IBAction func nextQuestionAction(_ sender: UIButton) {
    if sender.isSelected {
        
    }
}

CodePudding user response:

use UIButton in your @IBAction method like below

@IBAction func nextQuestionAction(_ sender: UIButton) {
    if sender.isSelected {
        // returns true value
    }
    else 
    {
       // returns false value
    }
}

or

@IBAction func nextQuestionAction(_ sender: Any) {
    if ((sender as AnyObject).isSelected) {
        // returns true value
    }
    else 
    {
       // returns false value
    }
}
  • Related