Lucas
Lucas

Reputation: 713

Swift if statement being re-executed when button title updated

So I have this very simple code, the button is set to the title "Title1" in IB

@IBAction func changeTitle(sender: AnyObject) {
    let button = sender as UIButton
    if (button.titleLabel == "Title1") {
        button.setTitle("Title2", forState: .Normal)

    } else {
        button.setTitle("Title1", forState: .Normal)
    }

}

So what's happening is that the first condition in the if statement gets executed, then the line of code updating the title of the button is hit, where then it goes back to the if statement, then finding it false, and skipping to the else {} now... I cannot figure out why this is happening.

Thanks in advance

Upvotes: 1

Views: 1135

Answers (1)

Steve Rosenberg
Steve Rosenberg

Reputation: 19524

This should work:

@IBAction func changeTitle(sender: AnyObject) {
    let button = sender as UIButton
    if (button.titleLabel?.text == "Title1") {
        button.setTitle("Title2", forState: .Normal)

    } else {
        button.setTitle("Title1", forState: .Normal)
    }
}

Upvotes: 2

Related Questions