在转到视图控制器之前为导航栏后退操作添加警报

问题描述 投票:0回答:3

所以我有一个添加条目 vc,对于后退按钮,我希望弹出一个警报来询问用户是否要继续,因为他们的信息将丢失。我一直在阅读并发现可以使用此功能,但它无法按我想要的方式工作。当视图加载并返回到主 vc 后,会出现警报。这是代码和一些图片。谢谢。

override func willMove(toParent parent: UIViewController?) {
    let alertController = UIAlertController(title: "Are You Sure?", message: "If You Proceed, All Data On This Page Will Be Lost", preferredStyle: .alert)
    let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
    alertController.addAction(action)
    self.present(alertController, animated: true)
}

swift navigation tableview back
3个回答
1
投票

您必须像这样在

viewDidload
中添加自定义后退按钮

   override func viewDidLoad() {
            super.viewDidLoad()
            let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.backAction(sender:)))
            self.navigationItem.leftBarButtonItem = newBackButton

        }

这是后退按钮的操作方法,因此您可以在此处添加警报并添加任何您想要的操作,如下所示:

@objc func backAction(sender: UIBarButtonItem) {

    let alertController = UIAlertController(title: "Are You Sure?", message: "If You Proceed, All Data On This Page Will Be Lost", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "Ok", style: .default) { (result : UIAlertAction) -> Void in
        self.navigationController?.popViewController(animated: true)
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)
    alertController.addAction(okAction)
    self.present(alertController, animated: true)
}

0
投票

从 iOS16+ 开始,借助 backAction,您可以向后退按钮添加自定义操作。

以下是文档的内容:

如果导航栏中已出现后退按钮,则设置此属性将替换其操作,而不修改其外观。

因此,在您的

viewDidLoad
或适当的地方,您可以添加以下代码:

navigationItem.backAction = UIAction { [weak self] _ in
    // show your alert here
}

不再需要添加自定义栏按钮,其缺点是没有完全相同的设计并且还会丢失交互式弹出窗口。


-1
投票
override func viewDidLoad {
        super.viewDidLoad()
        self.navigationItem.hidesBackButton = true
        let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(YourViewController.back(sender:)))
        self.navigationItem.leftBarButtonItem = newBackButton
    }

    func back(sender: UIBarButtonItem) {
        let alertController = UIAlertController(title: "Are You Sure?", message: "If You Proceed, All Data On This Page Will Be Lost", preferredStyle: .alert)
        let stayAction = UIAlertAction(title: "Stay", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in
          print("Stay")
        }
        let leaveAction = UIAlertAction(title: "GO Back", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in
           self.navigationController?.popViewController(animated: true)
        }
        self.present(alertController, animated: true)
    }
© www.soinside.com 2019 - 2024. All rights reserved.