ios - Swift 更新 UILabel 与 dispatch_async 不工作

标签 ios swift uilabel dispatch-async

为什么这行不通?

dispatch_async(dispatch_get_main_queue(), {
    self.timeStringLabel.text = "\(self.timeStringSelected)"

    println(self.timeStringLabel.text)
})

我正在尝试更新 Swift 中的标签,但标签的 UI 从未改变。我一直在谷歌上搜索,但找不到任何不使用 dispatch_async 的响应。我究竟做错了什么?

第一次编辑:我错了。我没有打印更新的文本。文本永远不会改变。如果有帮助,它总是打印出 Optional("0")。默认值为 Storyboard 中定义的 0。

我已经尝试过使用和不使用 dispatch_async 都没有成功。我也尝试添加 self.timeStringLabel.setNeedsDisplay() 更新文本后立即,但这也不起作用。

编辑 2:这是完整的函数 + UILabel 声明

@IBOutlet weak var timeNumberLabel: UILabel!

@IBAction func timeNumberButtonPressed(sender: UIButton) {

    println("Number Selected. Tag \(sender.tag)")

    dispatch_async(dispatch_get_main_queue()) {

        self.timeNumberOneButton.selected = false
        self.timeNumberTwoButton.selected = false
        self.timeNumberThreeButton.selected = false
        self.timeNumberFourButton.selected = false

        if sender.tag == 0{
            self.timeNumberSelected = 0
        } else if sender.tag == 1 {
            self.timeNumberSelected == 5
        } else if sender.tag == 2 {
            self.timeNumberSelected == 10
        } else {
            self.timeNumberSelected == 24
        }

        sender.selected = true

        self.timeNumberLabel.text = "\(self.timeNumberSelected)"

        self.timeNumberLabel.setNeedsDisplay()


        println(self.timeNumberLabel.text)
    }
}

标签清晰可见,如图所示。我不认为实现起来会这么难,但我错了。我愿意打赌我错过了一些非常简单的事情。

enter image description here

最佳答案

尝试添加行

self.timeStringLabel.setNeedsDisplay()

(标签更改后)

由于代码是异步运行的,界面更新方法可能会错过更改而不显示它(特别是如果在标签更改之前发生了一段耗时的代码)。添加此代码会强制界面检查并显示它可能遗漏的任何更改。

这应该在任何更改接口(interface)的异步任务之后使用,因为任务的运行可能与接口(interface)方法重叠,导致错过更改。

*感谢 iOS Development Journal

关于ios - Swift 更新 UILabel 与 dispatch_async 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30564666/

相关文章:

ios - 如何从 collectionView 中选择项目并将其添加到 SCNScene 中?

Swift tableView 滚动到行为我的 tableview 的内容偏移值提供了错误的值

ios - 如何通过点击改变UILabel的内容?

ios - 如何将 UILabel 重新定位在与另一个 UILabel 完全相同的位置

ios - 在 CoreData 中存储位置 (Swift)

ios - 尝试向服务器发送 telnet 命令

ios - 点击手势识别器干扰清除按钮

iphone - 移动自定义注释以显示用户位置

arrays - 如果属性值存在于另一个对象数组中,则快速过滤对象数组

ios - 在 UITableViewCell 中水平居中放置两个 UILabel