user16384840
user16384840

Reputation: 57

ViewWillDisappear() not working as intented

I'm trying to implement something similar to OnBackPressed from Android and this is what I've got so far:

public override void ViewWillDisappear(bool animated)
{
    if(isTrue)
    {
        // Go to previous controller
        base.ViewWillDisappear(animated)
    } 
    else 
    {
        // Stay on the current controller
    }
}

However, this does not seem to work as base.ViewWillDisappear() is always called. How can I prevent that?

Upvotes: 1

Views: 69

Answers (2)

David Prusa
David Prusa

Reputation: 53

You can always make a custom back button.

 override func viewDidLoad() {
    super.viewDidLoad()
    let customBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(MyViewController.backClicked(sender:)))
    self.navigationItem.leftBarButtonItem = customBackButton
    self.navigationItem.hidesBackButton = true
  }


  func backClicked(sender: UIBarButtonItem) {
    if(isTrue){
      // Go to previous controller
      _ = navigationController?.popViewController(animated: true)
    }
    else{
      // Stay on the current controller
    }
  }
  

Upvotes: 0

Ivan I
Ivan I

Reputation: 9990

The strict answer is that you can't. Swipe right gesture will always go back, no matter what.

Other than that if you are fine just with disabling this on the back button press, you can use the custom button trick in David's answer.

Upvotes: 1

Related Questions