首页 > 解决方案 > 取消滑动将导致视图操作停止使用 SwiftUI

问题描述

它使用导航,即使您在屏幕中间滑动,也可以返回,如此处的代码所示。在这种情况下,如果导航的 viewControllers 中存在 SwiftUI 视图,如果您在中间取消返回操作,则 SwiftUI 视图将不会接受该操作。有针对这个的解决方法吗?

https://gist.github.com/policante/33a2d11b0501052d230c1f213dcacde3

class BaseNavigationController: UINavigationController, UINavigationControllerDelegate {
    
    var interactivePopTransition: UIPercentDrivenInteractiveTransition!
    
    override func viewDidLoad() {
        self.delegate = self
    }
    
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
        addPanGesture(viewController)
    }
    
    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        if operation == .pop {
            return NavigationPopTransition()
        }else{
            return nil
        }
        
    }
    
    func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
        if animationController.isKind(of: NavigationPopTransition.self) {
            return interactivePopTransition
        }else{
            return nil
        }
    }
    
    private func addPanGesture(_ viewController: UIViewController){
        let popRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanRecognizer(recognizer:)))
        viewController.view.addGestureRecognizer(popRecognizer)
    }
    
    @objc func handlePanRecognizer(recognizer: UIPanGestureRecognizer){
        var progress = recognizer.translation(in: self.view).x / self.view.bounds.size.width
        progress = min(1, max(0, progress))
        print(progress)
        if recognizer.state == .began {
            self.interactivePopTransition = UIPercentDrivenInteractiveTransition()
            self.popViewController(animated: true)
        }else if recognizer.state == .changed {
            interactivePopTransition.update(progress)
        }else if recognizer.state == .ended || recognizer.state == .cancelled {
            if progress > 0.2 {
                interactivePopTransition.finish()
            }else{
                interactivePopTransition.cancel()
            }
            interactivePopTransition = nil
        }
    }
}
struct SampleView: View {
    var body: some View {
        NavigationLink(
            destination: SampleView(),
            label: {
                Text("LINK")
            })
    }
}

let view: UIHostingController = UIHostingController(rootView: SampleView())
let nav = BaseNavigationController[enter image description here][1](rootViewController: view)
present(nav, animated: true, completion: nil)

转载 gif

标签: swiftswiftuiuinavigationcontroller

解决方案


推荐阅读