2017-06-08 24 views
0
func displayalert(title:String, message:String, vc:UIViewController) 
{ 
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
    alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in 

     self.dismiss(animated: true, completion: nil) 

    }))) 

    vc.present(alert, animated: true, completion: nil) 


} 


this is the function i have used.i tried to call it like this, 

displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:validateOTPViewController()) 

它返回錯誤「不良訪問」。 vc.present像循環一樣運行。我不明白問題是什麼。創建全局顯示報警功能,並從任何視圖控制器調用它

+0

問題是什麼? –

+0

將此方法創建爲靜態方法,並將其類添加到項目的.pch文件中。你將可以訪問任何課程。 – Priyal

+0

這是糟糕的編程習慣。將代碼放入'UIViewController'的擴展中,刪除'vc'參數並刪除'present'行中的'vc.'。 – vadian

回答

0

我運行你的代碼,它工作正常。我會在vc中通過自我。

self.displayalert(title: "Title", message: "Some Message", vc: self) 

您也可以UIViewController-

的延伸
extension UIViewController { 
      // Your Function... 
    } 

現在,您可以全局訪問任何視圖控制器此功能,只需通過typing-

self.displayalert(title: "Title", message: "Some Message", vc: self) 
+0

你也可以做一個UIViewController的擴展,並把你的函數放在那裏,這樣你就可以從任何視圖控制器中全局訪問這個函數,只需輸入self.displayalert(title:「Title」,message:「Some Message」,vc :self) –

+0

它的工作..非常感謝你兄弟。 – faheem

1

您正在將validateOTPViewController的新實例傳遞給displayalert函數。

將其更改爲:

displayalert1(title:"dsfvasdcs", message:"easfSDXCSDZX", vc:self) 

這將當前視圖控制器傳遞給函數,而不是尚未提出一個新的。

1

斯威夫特4
使用您的函數創建UIViewController的擴展,以顯示具有所需參數的警報ameter參數

extension UIViewController { 

     func displayalert(title:String, message:String) { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in 

      alert.dismiss(animated: true, completion: nil) 

     }))) 

     self.present(alert, animated: true, completion: nil) 


     } 
} 


現在從您的視圖控制器調用這個函數:

class TestViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.displayalert(title: <String>, message: <String>) 
    } 
} 
相關問題