Confirm back button on UINavigationController

前端 未结 7 1855
南旧
南旧 2020-12-09 18:03

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

7条回答
  •  借酒劲吻你
    2020-12-09 18:54

    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 :)

提交回复
热议问题