在ViewController之外显示UIAlertController [英] show UIAlertController outside of ViewController
本文介绍了在ViewController之外显示UIAlertController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法显示我的UIAlertController,因为我试图在不是ViewController的类中显示它。
I have trouble to display my UIAlertController because I'm trying to show it in a Class which is not an ViewController.
我已经尝试添加它:
var alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
哪个不行......
我找不到任何对我有用的解决方案。
Which is not working... I didn't find any solution that worked for me yet.
推荐答案
我在 UIAlertController上写了这个
带回扩展名
show()
。
它使用递归来查找当前的顶视图控制器:
I wrote this extension
over UIAlertController
to bring back show()
.
It uses recursion to find the current top view controller:
extension UIAlertController {
func show() {
present(animated: true, completion: nil)
}
func present(#animated: Bool, completion: (() -> Void)?) {
if let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController {
presentFromController(rootVC, animated: animated, completion: completion)
}
}
private func presentFromController(controller: UIViewController, animated: Bool, completion: (() -> Void)?) {
if let navVC = controller as? UINavigationController,
let visibleVC = navVC.visibleViewController {
presentFromController(visibleVC, animated: animated, completion: completion)
} else
if let tabVC = controller as? UITabBarController,
let selectedVC = tabVC.selectedViewController {
presentFromController(selectedVC, animated: animated, completion: completion)
} else {
controller.presentViewController(self, animated: animated, completion: completion);
}
}
}
现在它很简单:
var alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
alertController.show()
编辑:
对于Xcode 8.0& Swift 3:
For Xcode 8.0 & Swift 3:
extension UIAlertController {
func show() {
present(animated: true, completion: nil)
}
func present(animated: Bool, completion: (() -> Void)?) {
if let rootVC = UIApplication.shared.keyWindow?.rootViewController {
presentFromController(controller: rootVC, animated: animated, completion: completion)
}
}
private func presentFromController(controller: UIViewController, animated: Bool, completion: (() -> Void)?) {
if let navVC = controller as? UINavigationController,
let visibleVC = navVC.visibleViewController {
presentFromController(controller: visibleVC, animated: animated, completion: completion)
} else
if let tabVC = controller as? UITabBarController,
let selectedVC = tabVC.selectedViewController {
presentFromController(controller: selectedVC, animated: animated, completion: completion)
} else {
controller.present(self, animated: animated, completion: completion);
}
}
}
这篇关于在ViewController之外显示UIAlertController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文