Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios UIButton文本内容每秒钟都会重置一次更新_Ios_Swift_Uibutton_Uikit - Fatal编程技术网

Ios UIButton文本内容每秒钟都会重置一次更新

Ios UIButton文本内容每秒钟都会重置一次更新,ios,swift,uibutton,uikit,Ios,Swift,Uibutton,Uikit,我试图用测试值更新一个按钮,我注意到每秒钟更新一次按钮标题文本都会显示测试值一小部分秒,然后重置为按钮的默认值 这似乎是一个bug,但我想看看是否有更简单的解释。 我试着在按下按钮前等待10秒钟,但这似乎一直在发生 如何使UIButton按预期运行 import UIKit class ViewController: UIViewController { var testEntry = "its working" @IBOutlet weak var testButton:

我试图用测试值更新一个按钮,我注意到每秒钟更新一次按钮标题文本都会显示测试值一小部分秒,然后重置为按钮的默认值

这似乎是一个bug,但我想看看是否有更简单的解释。 我试着在按下按钮前等待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)"
        }
    }

是github项目。

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

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

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

您应该使用以下方法设置按钮标题文本

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

而不是
标题标签
属性。

Swift 5

self.testButton.setTitle("hello", for: .normal)

带状态alwyz的setTitle方法可行,但直接将值设置为TitleLabel有时会有点力不从心。听起来,如果功能无法持续工作,则应该删除设置的标题。我在objective C和Swift中也多次遇到类似问题,因此分享了我的经验,并给出了可爱的解释。我以前确实有过这个问题,但是忘记了。苹果真的应该修复这个问题,否则就不赞成苹果提交的itBug报告。由于试图设置只读属性,直接分配标题文本的尝试将无法编译。