Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Prevent back event in UIViewController

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.

like image 695
Yetispapa Avatar asked Apr 24 '17 09:04

Yetispapa


1 Answers

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
    }
}
like image 100
Andrew Avatar answered Oct 10 '22 23:10

Andrew