如何强制 UILabel 更新其文本?

How can I force an UILabel to update its text?

我正在使用 Swift 为 iOS 编写代码。当我单击一个按钮时,我想将 UILabel 中的文本设置为更改两次;一次是在我们进入函数调用时,第二次是在调用完成之前。像这样:

@IBAction func myButton(_ sender: Any) {

    // 1. Display "Please Wait..." in a UILabel

    // 2. Compute a value by calling a function 
    //    (it is slow, takes several seconds so 
    //    we need the please wait text to tell 
    //    the user it is doing something)

    // 3. Display the results from the computation 
    //    in the same UILabel as above

我 运行 遇到的问题是,在我调用慢速函数之前设置 UILabel 的文本 (myLabel.text = "Please Wait"),然后在结果出现时再次设置它只会显示结果文本,因为程序在第一次设置后没有重新绘制屏幕("Please Wait" 文本)。 Apple 提到它仅使用 .text 属性 的最新更新,因此这是预期的行为。在我的函数中完成我想做的事情的最简单方法是什么?我对线程了解不多,因为我是初学者,所以对我放轻松。 :) 设置文本 "Please Wait..." 后是否可以调用魔术函数,以便它立即更新 UILabel?

要实现这一点,您需要这个结构

self.display.text = "wait" 
 // do task in background queue like 
DispatchQueue.global(qos: .background).async {
   callSlow() 
   DispatchQueue.main.async {
      self.display.text = "done" 
   }
}

您的长计算似乎发生在主线程中,因此它会阻止更新标签