Action to Navigation bar back button

前端 未结 6 1530
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 20:06

I want to show an alert with Confirmation when user clicks on back button. This is how I\'m trying to add action.

self.navigationItem.hidesBackButton = true
         


        
6条回答
  •  抹茶落季
    2020-12-19 20:55

    I found a solution!

    I tested it on iOS 11 and iOS 13 and it works fine :)

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

提交回复
热议问题