如何在Swift的子视图类中创build一个警报?

我有一个视图控制器,其中包含一个子视图。 而在子视图类中,当满足条件时,可能需要popup警告。

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函数来显示警报,因为我的子视图不是控制器类。 我应该以某种方式创build一个在子视图内的父控制器的一周引用? 实施这种参考的最佳做法是什么?

有几种方法可以在UIView捕获UIViewController

  1. 您可以将任何视图控制器作为委托来显示警报;
  2. 您可以将视图控制器的引用传递给您的视图; 和
  3. 一般来说,您可以随时在代码中的任意位置获取rootViewController

您需要在同一视图控制器上调用dismissViewControllerAnimated(_: completion:) ,以便稍后closures警报。

因此,我会为你的情况做一个这样的快速解决scheme:

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