我有一个包含子视图的视图控制器。在子视图类中,当满足某些条件时,我可能需要弹出警报。
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函数来显示警报。我应该以某种方式在子视图内创建对父控制器的一周引用吗?实施此类参考的最佳实践是什么?
有几种方法可以使UIViewController您抓住自己的生活UIView。
UIViewController
UIView
rootViewController
dismissViewControllerAnimated(_: completion:)当您以后想要关闭警报时,需要在同一视图控制器上调用。
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) } }