我有一个包含子视图的视图控制器。在子视图类中,我可能需要在满足某些条件时弹出警报。
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函数来显示警报,因为我的子视图不是控制器类。我应该以某种方式在子视图中创建对父控制器的周引用吗?实施此类参考的最佳做法是什么?
答案 0 :(得分:0)
有几种方法可以捕捉UIViewController
中的UIView
。
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)
}
}
答案 1 :(得分:0)
快捷键4
只需在根视图控制器的UIApplication窗口中显示警报:
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)