Swift系统返回按钮事件拦截实现

想要自定义 iOS 的返回按钮行为?这篇文章会教你怎么在 Swift 中实现系统返回按钮事件的拦截。其实,拦截返回按钮事件并不复杂,只需要通过重写popViewControllerAnimated(_:) 方法,或者自定义一个返回按钮,结合NotificationCenter来实现全局监听。这样,你可以在用户未保存数据时提醒他们,或者在退出时展示确认对话框。

例如,假设你要拦截返回按钮,你可以在自己的CustomNavigationController中重写popViewControllerAnimated(_:) 方法,判断用户是否符合返回条件,如果满足条件就调用父类的返回方法,否则就拦截它。

代码片段看起来是这样的:

class CustomNavigationController: UINavigationController {
  override func popViewControllerAnimated(_ animated: Bool) -> UIViewController? {
    if canPop() {
      return super.popViewControllerAnimated(animated)
    }
    return nil
  }

func canPop() -> Bool { let topViewController = topViewController if let vc = topViewController as? YourViewController { return vc.isDataSaved } return true } }

这样,当你调用popViewControllerAnimated时,就可以根据canPop()的返回值来决定是否执行返回操作。

,拦截返回事件挺,你可以灵活地控制用户的导航行为,提升用户体验。如果你的 App 中有多个页面需要这种拦截逻辑,使用通知中心全局监听会更加高效。

值得注意的是,替换系统的返回按钮也蛮常见的,你可以自定义一个按钮,控制返回行为,让用户体验更顺畅。其实这段代码也挺,像这样:

override func viewDidLoad() {
  super.viewDidLoad()
  navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(handleCustomBackButton))
}

@objc func handleCustomBackButton() { if canPop() { self.navigationController?.popViewController(animated: true) } }

你可以根据自己的需求,在这上面加上想要的逻辑。如果你还想了解更详细的技术实现,文中还有更多内容可以参考。

如果你正好在做类似的项目,照着这个思路来,拦截返回按钮事件真的不难。

zip
swift-系统返回按钮事件拦截Swift版本.zip 预估大小:18个文件
folder
BackBtnEventIntercept-master 文件夹
folder
BackBtnEventIntercept 文件夹
folder
BackBtnEventIntercept.xcodeproj 文件夹
folder
project.xcworkspace 文件夹
file
contents.xcworkspacedata 166B
file
project.pbxproj 18KB
folder
BackBtnEventIntercept 文件夹
folder
Assets.xcassets 文件夹
folder
AppIcon.appiconset 文件夹
file
Contents.json 1KB
file
main.m 346B
folder
UIViewController+BackBtnEventIntercept 文件夹
file
UIViewController+BackBtnEventIntercept.h 371B
file
UIViewController+BackBtnEventIntercept.m 1KB
file
AppDelegate.h 289B
file
AppDelegate.m 2KB
folder
Base.lproj 文件夹
file
LaunchScreen.storyboard 2KB
file
Main.storyboard 4KB
file
ViewController.h 227B
file
Info.plist 1KB
file
ViewController.m 1KB
folder
BackBtnEventInterceptTests 文件夹
file
Info.plist 680B
file
BackBtnEventInterceptTests.m 953B
file
LICENSE 1KB
file
.gitignore 1KB
file
README.md 2KB
zip 文件大小:19.16KB