在转到View Controller之前为Nav Bar后退操作添加警报

时间:2019-01-07 15:51:08

标签: swift navigation tableview back

因此,我有一个添加项vc,对于后退按钮,我希望弹出警报以询问用户是否要继续,因为他们的信息将丢失。我已经阅读并发现可以使用此功能,但无法正常使用。在加载视图时以及返回主vc之后,将出现警报。这是代码和一些图片。谢谢。

InitValue\((?:(\w+)\s*(?:,(?!\s*\))|(?=\s*\)))\s*)*\)

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:0)

您必须以这种方式在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)
}

答案 1 :(得分:-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)
    }