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.


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.


You should set the button title text by using the following method...

self.testButton.setTitle(self.testEntry, forState: .Normal)

instead of titleLabel property.

链接地址: http://www.djcxy.com/p/28226.html

上一篇: 使用UILabel制作UIButton Wrap

下一篇: UIButton文本内容不断重置每秒更新