Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton text content keeps resetting every second update

I am trying to update a button with a test value and I have noticed that every second update the button title text shows the test value for a fraction of a second but then resets to the Button's default value.

It seems to be a bug, but I wanted to see if there is a simpler explanation. I have tried waiting up to 10 seconds before pushing the button but this seems to be consistently occurring.

Any ideas how to make UIButton function as expected?

import UIKit

class ViewController: UIViewController {

    var testEntry = "its working"
    @IBOutlet weak var testButton: UIButton!
    @IBOutlet weak var testLabel: UILabel!

    @IBAction func runTest(sender:
        UIButton) {
        // The button value should equal the value of the label value, but every 2nd button press of the test button results in the title of the button value resetting to the default value
        dispatch_async(dispatch_get_main_queue()) {
            self.testLabel.text = "\(self.testEntry)"
            self.testButton.titleLabel?.text = "\(self.testEntry)"
        }
    }

Here is the github project.

like image 671
UKDataGeek Avatar asked Dec 15 '22 04:12

UKDataGeek


1 Answers

You shouldn't be directly setting the text of the button title label, you should only set the font directly onto the label. The text should be set by calling

func setTitle(_ title: String?, forState state: UIControlState)

The text toggles because you're selecting and de-selecting the button, which is switching between some of its states which have different titles.

like image 169
Wain Avatar answered Mar 15 '23 23:03

Wain