测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布最新发布 | 2016年10月 |
SPM支持 SPM | ✗ |
由 Dylan Bettermann 维护。
将 UIAlertView 的 show() 功能添加到 UIAlertController。
您是否需要不知道可见视图控制器的情况下显示一个通知?如果您想不起来的话,让我举个例子。
假设我们在 App Store 有一个应用程序,我们想要让用户知道有一个更新。我们怎么办?
AppDelegate.swift
func applicationDidBecomeActive(application: UIApplication) {
if update {
UIAlertView(title: "Update Available", message: "Would you like to update your app?", delegate: self, cancelButtonTitle: "Yes!").show()
}
}
简单,对吧?我们不需要担心哪个视图控制器是可见的。UIAlertView 似乎会找到可见的视图控制器并将其作为子视图添加。
UIAlertView 和系统警报可能实际上也会使用它们自己的 UIWindow,就像 DBAlertController 一样,但我不打算深入。
AppDelegate.swift
func applicationDidBecomeActive(application: UIApplication) {
if update {
let alertController = UIAlertController(title: "Update Available", message: "Would you like to update your app?", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Yes!", style: .Default, handler: nil))
window!.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
这会起作用……但是只有当根视图控制器的视图在窗口层次结构中时。
如果根视图控制器的视图不在窗口层次结构中呢?
015-05-13 08:09:58.923 DBAlertController[1002:15635] Warning: Attempt to present <UIAlertController: 0x7ff5f2e3a500> on <UINavigationController: 0x7ff5f2f24760> whose view is not in the window hierarchy!
源中有这个场景的示例。拉取它并尝试一下。
DBAlertController 通过在其自己的 UIWindow 上显示 UIAlertController 来解决上述问题。
将 DBAlertController.swift 复制并粘贴到您的项目中。
let alertController = DBAlertController(title: "DBAlertController", message: "Hello World!", preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
alertController.show()
以下是 show()
的完整签名
func show(animated flag: Bool = true, completion: (() -> Void)? = nil)
正如您所看到的,您还可以传递一个 animated 标志和一个完成闭包,这些都会传递给
presentViewController(alertController, animated: flag, completion: completion)
欢迎所有反馈。发送推文给我或用以下邮箱地址发送问题、评论或问题:[your_email@example.com](/cdn-cgi/l/email-protection#f195889d909fdf9394858594839c909f9fb1969c90989ddf929e9c)