我刚刚用ViewController类创建了一个单一视图应用程序项目.我想从位于我自己的类内的函数显示一个UIAlertController. 
  
 
这是我的课堂有一个警戒.
class AlertController: UIViewController
{
     func showAlert()
     { 
         var alert = UIAlertController(title: "abc",message: "def",preferredStyle: .Alert)
         self.presentViewController(alert,animated: true,completion: nil)
     }
} 
 这是执行警报的ViewController.
class ViewController: UIViewController 
{
   override func viewDidLoad() 
   {
       super.viewDidLoad()  
   }
   @IBAction func showAlertButton(sender: AnyObject)
   {
       var alert = AlertController()
       alert.showAlert()
   }
} 
 这是我得到的而不是美丽的警觉.
警告:尝试提交UIAlertController:0x797d2d20在Sprint1.AlertController:0x797cc500,其视图不在窗口层次结构中!
我该怎么办?
解决方法
 我们来看看你的视图层次结构.你有一个ViewController. 
 
然后,您正在创建一个AlertController,您不会将其添加到层次结构中,并且正在调用其上的实例方法,尝试使用AlertController作为呈现控制器来显示另一个控制器(UIAlertController).
        然后,您正在创建一个AlertController,您不会将其添加到层次结构中,并且正在调用其上的实例方法,尝试使用AlertController作为呈现控制器来显示另一个控制器(UIAlertController).
+ ViewController
    + AlertController (not in hierarchy)
        + UIAlertController (cannot be presented from AlertController) 
 为了简化你的代码
class ViewController: UIViewController {
   override func viewDidLoad() {
       super.viewDidLoad()  
   }
   @IBAction func showAlertButton(sender: AnyObject) {
       var alert = UIAlertController(title: "abc",preferredStyle: .Alert)
       self.presentViewController(alert,completion: nil)
   }
} 
 这将工作.
如果你需要AlertController的东西,你将必须将它添加到层次结构中,例如.使用addChildViewController或使用另一个presentViewController调用.
如果你想让类只是一个助手来创建警报,它应该是这样的:
class AlertHelper {
    func showAlert(fromController controller: UIViewController) { 
        var alert = UIAlertController(title: "abc",preferredStyle: .Alert)
        controller.presentViewController(alert,completion: nil)
    }
} 
 称为
var alert = AlertHelper() alert.showAlert(fromController: self)