呈现视图控制器并允许用户向后滑动

Present view controller and allow user to swipe back

目前,我正在展示一个新的视图控制器,如下所示:

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "MyViewController") as? MyViewController {

    // Present fullscreen
    viewController.modalPresentationStyle = .fullScreen
    
    self.present(viewController, animated: true, completion: nil)
}

但是,这不允许我从左侧滑动以返回到上一个控制器。如何启用此行为?

更新

这是我的代码:

@objc func onNextButtonTapped(sender: UITapGestureRecognizer) {
    let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "MyViewController") as? MyViewController {
        self.navigationController?.pushViewController(viewController, animated:true)
    }
}

您需要将视图控制器推送到该行为的导航堆栈。

let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
if let viewController = mainStoryboard.instantiateViewController(withIdentifier: "MyViewController") as? MyViewController {
    navigationController?.pushViewController(viewController, animated: true)
}

要使其正常工作,您要放入此代码的视图控制器必须嵌入到 UINavigationController 中。要将视图控制器嵌入到导航控制器中,请确保所选视图控制器确实具有包含您的代码的 class。

嵌入后应该是这样的: