2

My application uses the NavigationController. On the back button press I would to check that a certain condition has been met. If it hasn't I want to warn the user that the work they've done won't be saved.

I'm trying to use the viewWillDisappear function to perform the logic etc.

However, I'm unsure how to stop the navigation taking place if the user wishes to cancel it.

benjiiiii
  • 478
  • 10
  • 33
  • You need to create your own left navigation button, in the handler check that condition and if you want to navigate then you would have to pop the screen manually. You cannot hijack the default back button for that. – Sulthan Apr 11 '18 at 15:21
  • Would the left navigation button cover the existing back button only on that view? – benjiiiii Apr 11 '18 at 15:22
  • It would replace the back button completely. – Sulthan Apr 11 '18 at 15:25
  • Does that not mean that it would check for the condition from every view? – benjiiiii Apr 11 '18 at 15:26
  • Now, it means you would set that specific button only on the view controller you need. – Sulthan Apr 11 '18 at 15:36
  • see https://stackoverflow.com/questions/8564924/confirm-back-button-on-uinavigationcontroller for example – Sulthan Apr 11 '18 at 15:39
  • You would also have to account for the fact that the user can swipe back from the edge of the screen to go back (without tapping the back button). It would be a bad user experience to remove the swipe edge gesture that's in almost all navigation controller views on iOS so it's something to consider if you really want/need this behavior. – Paolo Apr 11 '18 at 15:47
  • Good point! However, there application is being used by those without much tech experience and I doubt they will actually know about that feature. Removing it may not be the end of the world. – benjiiiii Apr 11 '18 at 15:49

1 Answers1

3

Provide your left bar button item in your viewcontroller's viewDidLoad(..) method. Whatever logic you will put in the leftBarButton's Selector method, your left button will work like that.

ex:

override func viewDidLoad(){
let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(self.backButtonAction(_:)))
self.navigationItem.leftBarButtonItem = backButton
}

@objc func backButtonAction(_ sender: UIBarButtonItem){
    // Your logic for navigation
}