How to manage code in ViewWillDisappear?

340 Views Asked by At

I am working in xamarin.ios. I want to show a confirmation popup when user click at back navigation button at top that if user is sure he wants to go back previous screen.

I override the ViewWillDisappear method and called my popup there, but still screen go back to previous screen, before user confirm it from the popup.

Popup shows and behind that screen get move to previous screen.

How I can manage it so that screen can't move until user confirm it from popup?

2

There are 2 best solutions below

0
On

You can't do what you want to do in viewWillDissappear. Instead, you can assign a custom action to your back button like this:

 self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .Done, target: self, action:#selector(self.displayConfirmation(sender:)))

Implement the selector:

func displayConfirmation(sender: AnyObject) {
    let alert = UIAlertController(title: "", message: "Go back?", preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: nil))
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { action in
         self.navigationController?.popViewController(animated: true)
    }))
    self.present(alert, animated: true, completion: nil)
}
0
On

viewWillDisappear is a function which is already part of a transition, which you can't cancel. What you can do instead, is hide the backBarButton and instead of it, provide a custom navigationItem.leftBarButton which also has a @IBAction assigned to it. In the @IBAction you implement the required functionality, like presenting the popup.