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?
CodePudding user response:
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
}
}
CodePudding user response:
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.