0

这是我当前的代码:

import UIKit

class classViewController: UIViewController {
  // The function i want to call in other view controllers..
  func alertView(title: String, message: String) {
    var alert:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (action) -> Void in                
            self.dismissViewControllerAnimated(true, completion: nil)
        }))
    self.presentViewController(alert, animated: true, completion: nil)
  }
}

在另一个视图控制器中,我已经做了一个IBAction来执行这个 alertView,我做了这个:

@IBAction func button(sender: AnyObject) {
  classViewController().alertView("title", message: "message")
}

当我运行应用程序时,点击按钮后出现此错误,但没有alertView

警告:尝试呈现不在窗口层次结构中的视图!

4

1 回答 1

0

正确的。如果要创建一个显示警报的全局类,则需要传入对当前视图控制器的引用,并在调用中使用它而不是“self”,例如presentViewController.

您的类可能不应该是 UIViewController 的子类,因为看起来您从未将它显示到屏幕上。

我创建了一个Utils类,它是NSObject.

它有一个showAlertOnVC看起来像这样的方法:

  class func showAlertOnVC(targetVC: UIViewController?, var title: String, var message: String)
  {
    title = NSLocalizedString(title, comment: "")
    message = NSLocalizedString(message, comment: "")
    if let targetVC = targetVC
    {
      let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
      let okButton = UIAlertAction(
        title:"OK",
        style: UIAlertActionStyle.Default,
        handler:
        {
          (alert: UIAlertAction!)  in
      })
      alert.addAction(okButton)
      targetVC.presentViewController(alert, animated: true, completion: nil)
    }
    else
    {
      println("attempting to display alert to nil view controller.")
      println("Alert title = \(title)")
      println("Alert message = \(message)")
    }
  }
于 2015-07-13T00:01:30.690 回答