2015-07-12 33 views
0

这是我当前的代码:使类包括像UIAlertView中,UIActivityIndi​​cator的功能,并呼吁他们回来的各种viewControllers

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后:

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

回答

0

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

你的类可能不应该是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)") 
    } 
    } 
+0

你长了问题correctly..sorry我是初学者..ü可以阐明它更多? –

+0

我在“viewController”这样的IBAction中调用了这个函数.. Utils.showAlertOnVC(ViewController(),title:“title”,message:“message”) 仍然收到相同的错误:/ –

+0

那是因为是错的。您的代码正在创建视图控制器的新实例并将其传递给方法。这是错误的。你应该从你的视图控制器调用我的方法,并自行传递。 –

相关问题