📜  向左滑动返回 iphone swift (1)

📅  最后修改于: 2023-12-03 14:50:41.425000             🧑  作者: Mango

向左滑动返回 iPhone Swift

在 iPhone 应用中,用户可以通过向左滑动屏幕返回上一个页面。这是一个很方便的功能,用户可以在不需要点击返回按钮的情况下返回上一个页面,提高了用户体验。在 Swift 中,我们可以使用 UINavigationController 来实现这一功能。

实现方法
  1. 打开你的 iPhone 应用项目,选择要添加左滑返回功能的视图控制器。

  2. 在该视图控制器下方添加以下代码:

if self.navigationController?.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) ?? false {
    self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}
  1. 在视图控制器中添加以下代码:
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    if self.navigationController?.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) ?? false {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
}
 
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
 
    if self.navigationController?.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) ?? false {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
}
  1. 在 Xcode 的右侧导航栏中找到 "Project" > "Targets" > "Build Settings",在 "Other Linker Flags" 中添加 "-ObjC"。

现在你的应用就已经具备了向左滑动返回的功能。

Markdown 代码片段
如果 self.navigationController?.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) ?? false {
    self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    if self.navigationController?.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) ?? false {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
}
 
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
 
    if self.navigationController?.responds(to: #selector(getter: UINavigationController.interactivePopGestureRecognizer)) ?? false {
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
}