UIButton文本内容不断重置每一次更新

UKD*_*eek 2 uibutton uikit ios swift

我正在尝试更新一个带有测试值的按钮,我注意到每一次更新按钮标题文本显示测试值只有几分之一秒,但随后重置为Button的默认值.

这似乎是一个错误,但我想看看是否有一个更简单的解释.我已经尝试在按下按钮之前等待10秒,但这似乎一直在发生.

有关如何使UIButton按预期运行的任何想法?

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)"
        }
    }
Run Code Online (Sandbox Code Playgroud)

是github项目.

Wai*_*ain 9

您不应该直接设置按钮标题标签的文本,只应将字体直接设置到标签上.应通过调用来设置文本

func setTitle(_ title: String?, forState state: UIControlState)
Run Code Online (Sandbox Code Playgroud)

文本切换是因为您正在选择和取消选择按钮,该按钮在具有不同标题的某些状态之间切换.