我有一个包含 subview 的 View Controller 。在 subview 类中,我可能需要在满足某些条件时弹出警报。
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 函数来显示警报,因为我的 subview 不是 Controller 类。我应该以某种方式在 subview 中创建对父 Controller 的周引用吗?实现此类引用的最佳做法是什么?
最佳答案
swift 4
只需在 Root View Controller 的 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)
关于ios - 如何在 Swift 的 subview 类中创建警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24584364/