UIAlertView 显示在 KeyWindow 的子视图下

UIAlertView showing under KeyWindow's subview

我在 keyWindow 上添加了自定义视图。如何在自定义视图上显示 UIAlertController? (现在警报只是在我的自定义视图下弹出。)

let customView = CustomView()
UIApplication.sharedApplication().keyWindow!.addSubview(customView)

let alert = UIAlertController(title: NSLocalizedString("Error", comment: ""), message: "", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(alert, animated: true, completion: nil)

我认为如果不直接向 windows 添加视图会更好,这里有一些原因:

  • 一个是您遇到的问题
  • 如果您在目标上部署 <=iOS7 windows 不会旋转,所以您可能会在错误的位置找到您的叠加视图

为避免这种情况,如果您真的想添加自定义视图,请使用 rootViewController.view 属性。

let customView = CustomView()
UIApplication.sharedApplication().keyWindow!.rootViewController.view.addSubview(customView)

我没有测试它,但是自定义视图应该处于警报之下,因为它在 rootviewcontreller 层次结构中。