如何将控制器传递给函数

时间:2016-02-29 21:40:34

标签: ios swift uiviewcontroller

您好我有一个实用工具类,我在其中声明了AlertViewFunction,如此

func displayAlertMessage(userMessage: String,//controller){
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
    let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
    myAlert.addAction(okAction);
    self.presentViewController(myAlert, animated: true, completion: nil)    
}

问题是我不能在这里使用self

self.presentViewController(myAlert, animated: true, completion: nil) 

我想将一个控制器传递给这个函数,所以我可以像这样使用

controller.presentViewController(myAlert, animated: true, completion: nil) 

如何从任何ViewController传递控制器。让我们说如果我在LoginViewController

Utility().displayAlertMessage(Message.INTERNETISNOTCONNECTED,//controller)

2 个答案:

答案 0 :(得分:2)

func displayAlertMessage(userMessage: String, controller: UIViewController)
{
    controller?.presentViewController(myAlert, animated: true, completion: nil)
}

jQuery(".myContent").hide()

答案 1 :(得分:1)

传入视图控制器作为函数的参数。

func displayAlertMessage(controller: UIViewController, title: String, message: String?) {
  let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
  let okAction =  UIAlertAction(title: "Ok", style: .Default, handler: nil)
  alert.addAction(okAction)
  controller.presentViewController(alert, animated: false, completion: nil)
}

或者,您甚至可以通过声明:

将警报返回给函数的调用者以进行进一步的自定义
func displayAlertMessage(title: String, message: String?) -> UIAlertController {
  let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
  let okAction =  UIAlertAction(title: "Ok", style: .Default, handler: nil)
  alert.addAction(okAction)
  return alert
}

class controller: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    let alert = displayAlertMessage("title", message: nil)
    presentViewController(alert, animated: true, completion: nil)
  }
}