Phil Hudson
Phil Hudson

Reputation: 3901

Reset viewcontroller on UINavigation Back

TL;DR:

How can I fully recreate/reset a view controller that I'm navigating back to from the automatically placed UINavigationController back button?

Hi guys,

I'm using UINavigation and the automatically generated back button. When a user presses the back button, I want the previous view controller in the navigation stack to be fully reinstantiated - similar to how you would create the view controller then push to it.

I've tried the following but have been unable to find a solution:

I have a temporary solution in place now using the following code, however from a UX perspective it is not right, as it relies on a custom button and an illogical animation from the push that makes the user think they are going further into the app rather than coming out, the code is below and recreates the VC fully (as you can see from the instantiation).

private func goToStoryBoard(name: String) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier(name)
    self.navigationController?.pushViewController(vc, animated: true)

}

UPDATE

It looks like the issue is with the way I am creating custom components - I initialise them once like below, but by doing it this way they will not update:

  class HomeMenuButton: UIButton { 
           required init?(coder aDecoder: NSCoder) { 
              super.init(coder: aDecoder)                                
              self.setTitleColor(InterfaceColors.MainFont, forState: .Normal) 
              self.titleLabel?.font = InterfaceFonts.ButtonFont 
      } 
}

Upvotes: 0

Views: 1380

Answers (1)

matt
matt

Reputation: 535027

Don't make a whole new view controller. Just implement viewWillAppear: to completely initialize the view. This will work the same both when the view controller's view initially appears and when it appears because the pushed view controller is being popped to reveal it.

(If any situations later arise where you don't want to reinitialize the view on viewWillAppear:, just raise a Bool flag on those occasions.)

Upvotes: 2

Related Questions