Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload a view controller when back from another view using tab bar

I have a common view used when the user opens the app (VC1). With a tab bar controller, I load another view (VC2) that can be used to update data visible in the previous one. When I go back on VC1 (which is stack), it does not reload with updated data.

I have tried to call the viewDidLoad in the viewWillAppear like so...

override func viewWillAppear(_ animated: Bool) {
    viewDidLoad()
}

It works, but it loads over the VC1 still on stack and the user can see the change (not good).

I suppose that to dismiss the VC1 would help, but I haven't found how to dismiss a view when using tab bar controller.

like image 852
Bastien Avatar asked Dec 14 '22 20:12

Bastien


1 Answers

Follow these steps to handle you view load setup every time your view will appear:
(VC1 = First View Controller)

  • Create a new function/method (named viewLoadSetup) in your VC1 and move all codes from viewDidLoad() to viewLoadSetup().
  • Now, Call viewLoadSetup() from viewWillAppear

    class VC1: UIViewController {
    
        override func viewDidLoad() {
           super.viewDidLoad()
           // viewLoadSetup()  you may call it from view did load also
        }
    
        override func viewWillAppear(_ animated: Bool) {
           super.viewWillAppear(animated)
           viewLoadSetup()
    
        }
    
    
         func viewLoadSetup(){
          // setup view did load here
         }
    
    
    }
    


If you want to call viewLoadSetup from viewDidLoad for one time, when your view controller is loaded, and then after every time from your viewWillAppear then,

class VC1: UIViewController {

    var isLoadingViewController = false

    override func viewDidLoad() {
        super.viewDidLoad()
        isLoadingViewController = true
        viewLoadSetup()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if isLoadingViewController {
            isLoadingViewController = false
        } else {
            viewLoadSetup()
         }
    }


    func viewLoadSetup(){
      // setup view did load here
    }


}
like image 55
Krunal Avatar answered Dec 16 '22 09:12

Krunal