在我的swift 2 app中,我在我的app delegate中设置了这个简单的代码:
func applicationDidBecomeActive(application: UIApplication) {
print("HERE I AM")
}
这很好用。如果我从背景到前景启动我的应用程序(变为活动状态),将显示打印行。
但现在我想实现在实际的查看视图控制器中显示警告消息。
我知道我设置了一个这样的警报控制器:
let alertController = UIAlertController(title: "MY TITLE", message: "MY TEXT", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { (action) in}
alertController.addAction(action)
self.presentViewController(alertController, animated: true, completion: nil)
}
但是如何在实际视图控制器中显示应用程序委托中的警报控制器?
答案 0 :(得分:0)
var topViewController = self.window?.rootViewController
while topViewController?.presentedViewController != nil
{
topViewController = topViewController?.presentedViewController
}
let alertController = UIAlertController(title: "TITLE", message: "TEXT", preferredStyle: .Alert)
let action= UIAlertAction(title: "OK", style: .Default) { (action) in}
alertController.addAction(action)
topViewController!.presentViewController(alertController, animated: true, completion: nil)
答案 1 :(得分:0)
如果应用程序变为活动状态,猜猜你要查找的是在ViewController中接收一些信息。您可以通过观察ViewController上的UIApplicationDidBecomeActiveNotification
来实现此目的。
class ViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showAlert), name: UIApplicationDidBecomeActiveNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showAlert() {
print("Show Alert")
}
}
希望这有帮助。