问题
I have changed the back button in my navigation bar in one of my view controllers to a custom button and gave that button an action to do when pressed by:
self.navigationItem.hidesBackButton = true
let backButton = UIBarButtonItem(image: UIImage(named: "backArrow"), style: .plain, target: self, action: #selector(self.back))
self.navigationItem.leftBarButtonItem = backButton
This worked perfectly and I was able to keep the back swipe to pop the view controller by using:
self.interactivePopGestureRecognizer?.isEnabled = true
self.interactivePopGestureRecognizer?.delegate = self
in my navigation controller file. Unfortunately, when I back swipe, I can not (or I haven't figured out) call on the back()
function in my view controller that changes the back button. How and where can I detect that I am swiping to go back so I can call on the back function in that specific view controller?
回答1:
Like this answer you can just subscribe to the gesture: https://stackoverflow.com/a/36893464/1484378
// In UINavigationController
override func viewDidLoad() {
super.viewDidLoad()
self.interactivePopGestureRecognizer?.addTarget(self, action:#selector(self.handlePopGesture))
}
@objc func handlePopGesture(gesture: UIGestureRecognizer) -> Void {
if gesture.state == .began {
back()
}
}
You will probably have to add some custom logic to access your view controller's back method like: if let vc = visibleViewController as? MyViewController { vc.back() }
来源:https://stackoverflow.com/questions/54082589/adding-an-action-to-back-swipes-swift-4