user3582742
user3582742

Reputation: 39

How can I force an UILabel to update its text?

I am using Swift to write code for iOS. When I click a button I want to set the text in an UILabel to change twice; once when we enter the function call and a second time just before the call is done. Something like this:

@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

The problem I run into is that setting the UILabel's text (myLabel.text = "Please Wait") before I call the slow function and then setting it again when the result is in will ONLY show the result text because the program did not re-draw the screen after the first setting of it ("Please Wait" text). Apple mentions that it only uses the last update to the .text property so it is an expected behavior. What is the simplest way to accomplish what I want to do in my function? I don't know much about threads as I am a beginner so go easy on me. :) Is there a magic function I can call after I set the text "Please Wait..." so that it updates the UILabel immediately?

Upvotes: 0

Views: 953

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100541

To achieve that you need this structure

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

As it appears that your long calculation occurs in main thread so it blocks updating the label

Upvotes: 1

Related Questions