2017-07-16 87 views
0

我有一個應用程序,其中包含大量的ViewController s。還有一組函數返回UIAlertControllers通知用戶有關他的帳戶的事件。 這裏是一個這樣的funtion的一個示例:爲某些ViewControllers提供訪問功能的最有效方法

func signInSuccessAlert() -> UIAlertController { 
     //signInSuccessAlert 
     let signInSuccessAlert = UIAlertController(title: "Success", message: "You have been successfully signed in!", preferredStyle: .alert) 
     signInSuccessAlert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil)) 
     return signInSuccessAlert 
    } 

我的目標是則能夠在同一行顯示這些UIAlertController秒。像這樣:

present(signInSuccessAlert(), animated: true, completion: nil) 

是什麼力量讓只提供給ViewController s表示他們需要這些功能的最佳方式?而不是全球宣佈它們。

+1

使協議聲明它們。然後在協議的擴展中實現它們。任何需要訪問的ViewController都應符合協議。 – AgRizzo

回答

0

您可以創建UIViewController的擴展並在那裏聲明所有這些函數。 事情是這樣的:

extension UIViewController 
{ 

    func signInSuccessAlert() -> UIAlertController { 
     //signInSuccessAlert 
     let signInSuccessAlert = UIAlertController(title: "Success", message: "You have been successfully signed in!", preferredStyle: .alert) 
     signInSuccessAlert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil)) 
     return signInSuccessAlert 
    } 

} 

這樣,所有你的viewcontrollers將有機會獲得這些功能。如果你想只允許訪問一些viewcontrollers,你將不得不使用評論中提到的AgRizzo等協議。

相關問題