I am using the storyboard for my app which is using UINavigationController. I would like to add a confirmation dialog to the default back button so
Try this solution:
protocol CustomNavigationViewControllerDelegate {
func shouldPop() -> Bool
}
class CustomNavigationViewController: UINavigationController, UINavigationBarDelegate {
var backDelegate: CustomNavigationViewControllerDelegate?
func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
return backDelegate?.shouldPop() ?? true
}
}
class SecondViewController: UIViewController, CustomNavigationViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
(self.navigationController as? CustomNavigationViewController)?.backDelegate = self
}
func shouldPop() -> Bool {
if (needToShowAlert) {
showExitAlert()
return false
} else {
return true
}
}
}
I tested it on iOS 11 and iOS 13 and it works fine :)