在解除视图之前显示UIAlert

时间:2016-10-28 08:59:14

标签: ios swift

我的视图正在通过导航栏上的上一个按钮被忽略。我认为正确的术语是视图从视图堆栈中弹出。在实际解除视图之前,我想显示一个UIAlert,要求用户设置他/她的地址。

我试过了,但UIAlert没有显示:

override func viewWillDisappear(animated: Bool) {
    if let currentUser = ApiManager.sharedInstance.currentUser {
        if !currentUser.hasAddress {
            let alert = UIAlertController(title: "Missing address", message: "We see you're stilling missing an address, would you like set it now?", preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: "yes".localized, style: .Default, handler: { (alertAction) in
                let newViewController = LocationViewController()
                newViewController.delegate = self
                self.navigationController?.pushViewController(newViewController, animated: true)
            }))

            alert.addAction(UIAlertAction(title: "no".localized, style: .Default, handler: nil))

            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

在我的控制台中打印以下内容:

2016-10-28 16:58:47.380 gaifong[17096:14515422] Warning: Attempt to present <UIAlertController: 0x7fd7037e4cb0> on <gaifong.ProfileViewController: 0x7fd7048cc000> whose view is not in the window hierarchy!

1 个答案:

答案 0 :(得分:1)

您应该在navigationItem上添加leftBarButtonItem并对leftBarButtonItem进行操作,以便处理此问题。

viewDidLoad

中的

self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.goBack))

// Then handle the button selection
func goBack() {
  if let currentUser = ApiManager.sharedInstance.currentUser {
    if !currentUser.hasAddress {
        let alert = UIAlertController(title: "Missing address", message: "We see you're stilling missing an address, would you like set it now?", preferredStyle: UIAlertControllerStyle.Alert)

        alert.addAction(UIAlertAction(title: "yes".localized, style: .Default, handler: { (alertAction) in
            // here you can pop to main controller
            self.navigationController?.popViewControllerAnimated(true)
        }))

        alert.addAction(UIAlertAction(title: "no".localized, style: .Default, handler: nil))

        self.presentViewController(alert, animated: true, completion: nil)
    }
}
}