i have a question about canceling the back event triggered from the back-button in a UIViewController. In Objective-C there was the following extension. I don't really know how to convert it to swift. What I tried to far was to override the backBarButton with my own functions but it's not working:
navigation.backBarButtonItem?.action = #selector(MyController.back)
navigation.backBarButtonItem?.target = self
I searched for something like a delegate function but I can't find anything for the backButton.
When i faced with this problem, i rewrited this extension to Swift 3
This solution keeps system back button with "<"
public protocol VCWithBackButtonHandler {
func shouldPopOnBackButton() -> Bool
}
extension UINavigationController: UINavigationBarDelegate {
public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
if viewControllers.count < (navigationBar.items?.count) ?? 0 {
return true
}
var shouldPop = true
let vc = self.topViewController
if let vc = vc as? VCWithBackButtonHandler {
shouldPop = vc.shouldPopOnBackButton()
}
if shouldPop {
DispatchQueue.main.async {[weak self] in
_ = self?.popViewController(animated: true)
}
} else {
for subView in navigationBar.subviews {
if(0 < subView.alpha && subView.alpha < 1) {
UIView.animate(withDuration: 0.25, animations: {
subView.alpha = 1
})
}
}
}
return false
}
}
Usage:
class ViewController: UIViewController,VCWithBackButtonHandler{
public func shouldPopOnBackButton() -> Bool {
return false
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With