最近在项目中碰到点击返回按钮时要先进行确认的需求,网上度了一下找到了相应的解决方案(代码下载地址:https://github.com/onegray/UIViewController-BackButtonHandler)。
不是自己写的代码,就不白话了,简单说一下用法:GitHub上下载地址后,将下载的代码导入到自己的项目中(我是直接拖进去的),代码是Objective-C的,所以需要在头文件中导入.h文件;然后在自己的控制器中重写navigationShouldPopOnBackButton方法即可。
我的控制器重写navigationShouldPopOnBackButton方法如下,供参考:
override func navigationShouldPopOnBackButton() -> Bool {
let alertView = LGAlertView(title: "", message: "退出支付将取消此次操作,点‘确认’继续退出,点‘取消’继续此次操作", style: .alert, buttonTitles: ["确定"], cancelButtonTitle: "取消", destructiveButtonTitle: nil, actionHandler: {
(alertView, text, buttonIndex) in
if buttonIndex == 0 {
var viewController:UIViewController?
for index in 0..<(self.navigationController?.viewControllers.count)! {
if self.navigationController?.viewControllers[index] is 自己的控制器类名 {
viewController = self.navigationController?.viewControllers[index]
}
}
self.navigationController?.popToViewController(viewController!, animated: true)
}
}, cancelHandler: nil, destructiveHandler: nil)
alertView.show(animated: true, completionHandler: nil)
return false
}
let alertView = LGAlertView(title: "", message: "退出支付将取消此次操作,点‘确认’继续退出,点‘取消’继续此次操作", style: .alert, buttonTitles: ["确定"], cancelButtonTitle: "取消", destructiveButtonTitle: nil, actionHandler: {
(alertView, text, buttonIndex) in
if buttonIndex == 0 {
var viewController:UIViewController?
for index in 0..<(self.navigationController?.viewControllers.count)! {
if self.navigationController?.viewControllers[index] is 自己的控制器类名 {
viewController = self.navigationController?.viewControllers[index]
}
}
self.navigationController?.popToViewController(viewController!, animated: true)
}
}, cancelHandler: nil, destructiveHandler: nil)
alertView.show(animated: true, completionHandler: nil)
return false
}