user7299543
user7299543

Reputation: 121

Update UIView before calling other function?

I am working in Swift. When a user presses a UIButton it calls a function ButtonPressed(). I would like ButtonPressed() to do two things:

  1. Update the UIView by removing the current buttons and texts, then uploading some new text.
  2. Call function TimeConsumingCalculation(). TimeConsumingCalculation is the complicated part of my app and does some calculations which take about 20 seconds or so to complete.

Right now, I have the code in the basic order:

ButtonPressed(){
self.Button.removeFromSuperview()
TimeConsumingCalculation()
}

However, it will not remove the button or do any other UI updates or additions until after the TimeConsumingCalculation is complete. I have read and attempted a few guides on closures and asynchronous functions, but have had no luck. Is there a special property with UIView that is causing it to be updated last?

As a side note - I have already attempted putting all UI actions in a separate function and calling it first. It doesn't work. The time consuming function does not take any variables from the buttons or UI or anything like that.

Thanks!

Upvotes: 1

Views: 219

Answers (1)

MikeG
MikeG

Reputation: 4044

It seems like timeConsumingCalculation() is blocking the main queue, which is in charge of UI updates. Try calling it like this instead and use the isHidden property to hide the button instead of removing it from the view completely.

ButtonPressed(){
   self.Button.isHidden = true
   DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
      self.timeConsumingCalculation()
   }
}

here you call timeConsumingCalculation() asynchronously on a background thread. The quality of service we give it is userInitiated, read more about quality of service classes here

Upvotes: 1

Related Questions