How to create an alert in a subview class in Swift?

被刻印的时光 ゝ 提交于 2019-11-29 12:29:42

there are couple of ways how you can catch a UIViewController in your UIView.

  1. you can make any of your view controllers as a delegate to show an alert;
  2. you can pass a view controller's reference to your view; and
  3. in general you can always grab the rootViewController anywhere in your code.

you need to call the dismissViewControllerAnimated(_: completion:) on the same view controller when you'd like to dismiss your alert later.

thus, I'd do such a quick solution for your case:

func move() {
    if !gameBoard.checkNextMoveExist() {

        let rootViewController: UIViewController = UIApplication.sharedApplication().windows[0].rootViewController

        var alert = UIAlertController(title: "Game Over", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Take Me Back", style: UIAlertActionStyle.Cancel, handler: {(action: UIAlertAction!) in
            rootViewController.dismissViewControllerAnimated(true, completion: nil)
            println("Taking user back to the game without restarting")
        }))
        alert.addAction(UIAlertAction(title: "New Game", style: UIAlertActionStyle.Destructive, handler: {(action: UIAlertAction!) in
            rootViewController.dismissViewControllerAnimated(true, completion: nil)
            println("Starting a new game")
            self.restartGame()
        }))
        rootViewController.presentViewController(alert, animated: true, completion: nil)
    }
}

Swift 4

Just present the alert in UIApplication windows in root view controller:

let title = "Some title"
let message = "body message"

let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Aceptar", style: .cancel, handler: nil)

alert.addAction(action)

UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!