2016-02-29 22 views
2

你好,我有我已经宣布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
Utility().displayAlertMessage(Message.INTERNETISNOTCONNECTED, controller: self) 

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

非常感谢您 – hellosheikh

+0

@hellosheikh我很高兴我能帮助! –

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) 
    } 
} 
+0

非常感谢你 – hellosheikh

+0

不客气。 –

+0

我一直在做第二种风格。第一个从来没有发生过我。感谢发布。 –

相关问题