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

前端 未结 2 1466
梦毁少年i
梦毁少年i 2020-12-20 05:35

I have a view controller which contains a sub-view. And inside the sub-view class, I may need to pop out an alert when some condition is satisfied.

class Gam         


        
相关标签:
2条回答
  • 2020-12-20 05:56

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-20 06:19

    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)
    
    0 讨论(0)
提交回复
热议问题