ios - 如何在 Swift 的 subview 类中创建警报?

标签 ios swift alert subview

我有一个包含 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/

相关文章:

iphone - 此应用程序在 ios 5.0 下开发并运行良好,但在 ios 4.3 下崩溃

ios - Git 克隆后 XCode 项目位置错误

javascript - 如果输入日期 2 <= 日期 1,则 JS 发出警报

javascript - 如何从警报中获取输入?

javascript - 当我从代码中删除警报时,jQuery 代码不起作用?

ios - 将 NSMutableArray 转换为具有相同顺序的 NSSet

iphone - 如何从 JSON 中获取的字典中获取信息 - Objective-C/IOS/xCode

ios - SWIFT:很难在 tableView 中显示数据

swift - 如何在应用程序退出时获取 DispatchQueue() 代码进行清理

ios - UIScrollView 自动布局不工作 contentView 的宽度