Action to Navigation bar back button

前端 未结 6 1521
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  梦毁少年i
    2020-12-19 21:08

    Call this line of code inside of your ParentViewController's viewDidLoad method not the ChildViewController

    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    

    Remove the following line of code from your ChildViewController

    self.navigationItem.hidesBackButton = true
    

    And you'll be Ok! If you need to create an action for this transition, I mean whenever the user taps the back button from your ChildViewController. Simply call this method inside of your ChildViewController

     override func didMove(toParentViewController parent: UIViewController?) {
        super.didMove(toParentViewController: parent)
    
        if parent == nil {
    
        } else {
    
        }
    }
    

    Edited:

    ChildViewController

     override func didMove(toParentViewController parent: UIViewController?) {
        super.didMove(toParentViewController: parent)
    
        if parent == nil {
            NotificationCenter.default.post(name: NSNotification.Name.init("Post"), object: nil)
        } else {
    
        }
    
    }
    

    ParentViewController

     override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        NotificationCenter.default.addObserver(self, selector: #selector(self.handler(notification:)), name: NSNotification.Name.init(rawValue: "Post"), object: nil)
    
    }
    
    func handler(notification: Notification) {
    
        let alertController = UIAlertController(title: "Hello", message: nil, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
        self.present(alertController, animated: true, completion: nil)
    
    }
    

    This is works but with a problem like so:

    Warning: Attempt to present on while a presentation is in progress!

    Therefore I don't recommended. Good luck

提交回复
热议问题