Hobbyist
Hobbyist

Reputation: 16182

UIButton#titleLabel reverts after being changed programmatically

I have an @IBOutlet which connects to a UIButton. In my code I have the following method which is executed whenever a user performs an action. I've managed to replace my code with some dummy functions to show you guys what my issue is.

To replicate this issue, I am using a subclass of UITableViewController, you can see it below:

class MyTableViewController : UITableViewController {

    @IBOutlet nextOrCreateButton: UIButton!

    var dummy = [1, 2]
    var index: Int = 0

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dummy.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCellWithIdentifier("TemplateCell") as UITableViewCell!
    }

    @IBAction func onNextClicked() {
        if dummy.count == (index + 1) {
            dummy.append(0)
        }
        index++
    }

    func updateUI() {
        if dummy.count == (index + 1) {
            print("Setting text to FOO")
            nextOrCreateButton.titleView?.text = "FOO"
            if dummy.count == 4 {
                print("Setting text to FOOBAR")
                nextOrCreateButton.titleView?.text = "FOOBAR"
                nextOrCreateButton.enabled = false
            }
        } else {
            print("Setting text to BAR")
            nextOrCreateButton.titleView?.text = "BAR"
        }
    }
}

The code above has a button that is clicked, and when it is clicked it will either move to the next dummy value, the dummy value isn't used for anything in this example, other than to show that changing the text doesn't work.

What happens is the code executes how it should (According to debug messages) but the button's text changes to what it's set to, and almost immediately changes back.

Clicking the button X times prints the following logs:

Setting text to BAR
Setting text to FOO
Setting text to FOO
Setting text to FOO
Setting text to FOOBAR

However, the button always quickly changes back to FOO, even after changing to "FOOBAR" as it says it does, the button doesn't even remain disabled as we set in the code.

Upvotes: 7

Views: 529

Answers (2)

MarkHim
MarkHim

Reputation: 5766

Don't do this on a UIButton

nextOrCreateButton.titleView?.text = "FOOBAR"

Always use

nextOrCreateButton.setTitle("FOOBAR", forState: UIControlState.Normal)

Or swift3

nextOrCreateButton.setTitle("FOOBAR", for: .normal)

Upvotes: 12

Tobi Nary
Tobi Nary

Reputation: 4596

Have you tried using setTitle(_ title: String?, forState state: UIControlState)?

Upvotes: 1

Related Questions