Search code examples
iosswiftuiviewuikit

How can I force update my UI immediately in Swift 5 using UIKit?


I ran into a problem with my UI, which is not updating immediately.

I am calling someCustomView.isHidden = false first. After that I create a new instance of a new View Controller. Inside the new VCs viewDidLoad(), I am loading a "new Machine Learning Model", which takes some time.

private func someFuncThatGetsCalled() {

    print("1")

    self.viewLoading.isHidden = false

    print("2")

    performSegue(withIdentifier: "goToModelVCSegue", sender: nil)

}

As soon as I press the button that calls this function, "1" and "2" is printed in the console. However the view is not getting visible before the viewDidLoad() of my new VC is finished.

Is there any possibility to force update a UIView immediately? setNeedsDisplay() did not work for me.

Thanks for your help!


Solution

  • A couple problems...

    If you have a view controller that "takes some time" to load, you should not try to do it in that manner.

    The app will be non-responsive and appear "frozen."

    A much better approach would be:

    • on someFuncThatGetsCalled()
      • hide viewLoading and replace it with an activity indicator (spinner, or something else that let's the user know the app is not stuck)
      • instantiate your ModelVC
      • when ModelVC has finished its setup, have it inform the current VC (via delegate)
      • current VC then shows / navigates to the already instantiated and prepared ModelVC

    Or, probably a better option... Move your time-consuming setup in ModelVC to a point after the view has appeared. You can show an activity indicator in viewDidLoad(). That is really the most common UX - you see it all the time when the new VC has to retrieve remote data to display - and it would fit wit what users have come to expect.