小编典典

如何在Swift的子视图类中创建警报?

swift

我有一个包含子视图的视图控制器。在子视图类中,当满足某些条件时,我可能需要弹出警报。

class GameViewController: UIViewController {
    @IBOutlet var gameBoardUIView: GameBoardUIView
    ...
}

class GameBoardUIView: UIView {
    ...
    func move() {
        if !gameBoard.checkNextMoveExist() {
            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
                println("Taking user back to the game without restarting")
            }))
            alert.addAction(UIAlertAction(title: "New Game", style: UIAlertActionStyle.Destructive, handler: {(action: UIAlertAction!) in
                println("Starting a new game")
                self.restartGame()
            }))
            // This is where the question is
            // self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

从代码中可以看到,由于我的子视图不是控制器类,因此无法调用presentViewController函数来显示警报。我应该以某种方式在子视图内创建对父控制器的一周引用吗?实施此类参考的最佳实践是什么?


阅读 243

收藏
2020-07-07

共1个答案

小编典典

有几种方法可以使UIViewController您抓住自己的生活UIView

  1. 您可以将任何视图控制器作为 委托 来显示警报;
  2. 您可以将视图控制器的 引用 传递给您的视图;和
  3. 通常,您始终rootViewController可以在代码中的任何位置进行抓取。

dismissViewControllerAnimated(_: completion:)当您以后想要关闭警报时,需要在同一视图控制器上调用。

因此,我将针对您的情况做一个如此快速的解决方案:

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)
    }
}
2020-07-07