Search code examples
iosswiftviewwilldisappear

Cancelling a View Disappearing using ViewWillDisappear


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.


Solution

  • 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
    }