我可以从IBAction中调用UIAlertController

时间:2019-04-26 17:02:08

标签: ios swift uialertcontroller ibaction

我正在尝试在我的应用上发出警报,但它不断向我发出如下警告,但它没有出现

Warning: Attempt to present <UIAlertController: 0x..> on <xyz.VC1: 0x..> whose view is not in the window hierarchy! 

逻辑是这样的:-

(VC1)中的IBAction调用公共函数(X)

(X)该函数执行一些操作和功能,并基于此函数称为公共函数(警告)

(警告)该功能应显示警报,但会给我先前的警告。

注意:如果我直接从IBAction中使用警报,则该警报会正常工作

显示警报:

func WAlert(){
  //  print("Wrong :("") // to be an alert
    let alert = UIAlertController(title: "S?", message: "Y", preferredStyle: UIAlertController.Style.alert)

    alert.addAction(UIAlertAction(title: "C", style: UIAlertAction.Style.default, handler: { _ in
        //Cancel Action
    }))
    alert.addAction(UIAlertAction(title: "out",
                                  style: UIAlertAction.Style.default,
                                  handler: {(_: UIAlertAction!) in
                                    //Sign out action
    }))
    present(alert, animated: true, completion: nil)

    //self.present(alert, animated: true, completion: nil)
    //VC1.present(alert, animated: true, completion: nil)

1 个答案:

答案 0 :(得分:0)

您可能需要让该函数返回警报,而不是先显示警报,然后再从VC1中显示(self.present)。正如 Teja Nandamuri 在评论中提到的那样,必须从可见的UIViewController中发出警报。

根据评论进行了修订: 您可以在单独的功能(如WAlert)中生成警报,但即使在IBAction中,也可以将其显示在VC1中。例如,在操作中您将拥有:

let alert = WAlert()
self.present(alert, animated: true)

您需要按以下方式更改WAlert:

func WAlert() -> UIAlertController {
    let alert = UIAlertController(title: "S?", message: "Y", preferredStyle: UIAlertController.Style.alert)

    alert.addAction(UIAlertAction(title: "C", style: UIAlertAction.Style.default, handler: { _ in
        //Cancel Action
    }))
    alert.addAction(UIAlertAction(title: "out", style: UIAlertAction.Style.default, handler: {(_: UIAlertAction!) in
        //Sign out action
    }))
    return alert
相关问题