2016-02-29 44 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

我一直在做第二種風格。第一個從來沒有發生過我。感謝發佈。 –

相關問題