代码之家  ›  专栏  ›  技术社区  ›  El Tomato

防止ViewController切换回上一个

  •  0
  • El Tomato  · 技术社区  · 3 年前

    我有一个简单的示例iOS应用程序,有两个视图控制器( UIViewController )如下所述。

    //HomeViewController
    import UIKit
    
    class HomeViewController: UIViewController {
        // MARK: - IBAction
        @IBAction func goSecondTapped(_ sender: UIButton) {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            if let controller = storyboard.instantiateViewController(withIdentifier: "SecondNavigator") as? UINavigationController {
                if let viewController = controller.topViewController as? SecondViewController {
                    self.navigationController?.pushViewController(viewController, animated: true)
                }
            }
        }
        
        
        // MARK: - Life cycle
        override func viewDidLoad() {
           super.viewDidLoad()
        }
    }
    
    //SecondViewController
    import UIKit
    
    class SecondViewController: UIViewController {
        // MARK: - Life cycle
        override func viewDidLoad() {
           super.viewDidLoad()
        }
    }
    

    enter image description here

    所以我只想在点击按钮时切换到SecondViewController(转到Second)。问题是,如果我只是用手指从左向右滑动第二个视图,我就可以在不点击左上角的“后退”按钮的情况下返回HomeViewController。有什么办法可以防止这种情况吗?我只想在点击“返回”时返回HomeViewController。谢谢。

    0 回复  |  直到 3 年前
        1
  •  1
  •   Ckitakishi    3 年前

    你有没有试过禁用 interactivePopGestureRecognizer ?

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }