我们如何在没有用户输入的情况下创建和关闭 UIAlertController? (Swift)

How do we create and dismiss an UIAlertController without user input? (Swift)

我一直在查找有关 UIAlertController 的大量教程。到目前为止,我发现的方法是通过将 UIAlertController 链接到按钮或标签来激活它,然后调用 IBAction。

我尝试复制代码以在用户进入应用程序时自动弹出警报(我想询问用户是否想完成教程)。但是,我不断收到错误消息:

Warning: Attempt to present UIAlertController on MainViewController whose view is not in the window hierarchy!

然后我尝试通过addChildViewController 和addSubview 将UIAlertController 添加到MainViewController。但是,我收到错误消息:

Application tried to present modally an active controller

我发现我不能使用presentViewController函数,所以把它注释掉了。

显示了 UIAlertController,但是当我尝试单击取消或从不按钮时,出现此错误。

Trying to dismiss UIAlertController with unknown presenter.

我真的很难过。有人可以分享我做错了什么吗?太感谢了。这是代码。

    func displayTutorial() {

    alertController = UIAlertController(title: NSLocalizedString("tutorialAlert", comment: ""), message: NSLocalizedString("tutorialMsg", comment: ""), preferredStyle: .ActionSheet)

    self.addChildViewController(alertController)
    self.view.addSubview(alertController.view)
    alertController.didMoveToParentViewController(self)
    alertController.view.frame.origin.x = self.view.frame.midX
    alertController.view.frame.origin.y = self.view.frame.midY
   //alertController.popoverPresentationController?.sourceView = self.view*/


    let OkAction = UIAlertAction(title: NSLocalizedString("yesh", comment: ""), style: .Destructive) { (action) in

    }
    alertController.addAction(OkAction)

    let cancelAction = UIAlertAction(title: NSLocalizedString("notNow", comment: ""), style: .Destructive) { (action) in
        //println(action)
        self.tutorial = 1
        self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
    }

    alertController.addAction(cancelAction)

    let neverAction = UIAlertAction(title: NSLocalizedString("never", comment: ""), style: .Cancel) { (action) in
        self.tutorial = 1
    }
    alertController.addAction(neverAction)


    //self.presentViewController(alertController, animated: false) {}

}

我找到了解决方案。显然,我无法从 func viewDidLoad 调用 UIAlertController。我必须从 viewDidAppear 调用函数。所以我现在的代码是

override func viewDidAppear(animated: Bool) {
    if tutorial == 0 {
        displayTutorial(self.view)
    }
}

func displayTutorial(sender:AnyObject) {

    let alertController = UIAlertController(title: NSLocalizedString("tutorialAlert", comment: ""), message: NSLocalizedString("tutorialMsg", comment: ""), preferredStyle: .ActionSheet)


    let OkAction = UIAlertAction(title: NSLocalizedString("yesh", comment: ""), style: .Destructive) { (action) in

    }
    alertController.addAction(OkAction)

    let cancelAction = UIAlertAction(title: NSLocalizedString("notNow", comment: ""), style: .Default) { (action) in
        //println(action)
        self.tutorial = 1
        self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
    }

    alertController.addAction(cancelAction)

    let neverAction = UIAlertAction(title: NSLocalizedString("never", comment: ""), style: .Cancel) { (action) in
        self.tutorial = 1
    }
    alertController.addAction(neverAction)

    self.presentViewController(alertController, animated: true, completion: nil)

    if let pop = alertController.popoverPresentationController {
        let v = sender as UIView
        pop.sourceView = view
        pop.sourceRect = v.bounds
    }
}

感谢这篇帖子:Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

下面带有扩展的 UIAlertController 将帮助您显示具有动态按钮数量的警报以及选定索引的完成处理程序

extension UIViewController {

func displayAlertWith(message:String) {
    displayAlertWith(message: message, buttons: ["Dismiss"]) { (index) in
    }
}

func displayAlertWith(message:String, buttons:[String], completion:((_ index:Int) -> Void)!) -> Void {
    displayAlertWithTitleFromVC(vc: self, title: Bundle.main.infoDictionary!["CFBundleDisplayName"] as! String, andMessage: message, buttons: buttons, completion: completion)
}

func displayAlertWithTitleFromVC(vc:UIViewController, title:String, andMessage message:String, buttons:[String], completion:((_ index:Int) -> Void)!) -> Void {

    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    for index in 0..<buttons.count    {

        let action = UIAlertAction(title: buttons[index], style: .default, handler: {
            (alert: UIAlertAction!) in
            if(completion != nil){
                completion(index)
            }
        })
        alertController.addAction(action)
    }

    DispatchQueue.main.async {
        vc.present(alertController, animated: true, completion: nil)
    }
}

}

如果您需要自动关闭警报,您可以在延迟一段时间后在呈现的视图控制器上调用 dismiss

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
        vc.dismiss(animated: true, completion: nil)
    }

希望这对您有所帮助。