Adding an action to back swipes swift 4

邮差的信 提交于 2019-12-13 12:33:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!