2017-02-19 38 views
0

我想在我的應用程序啓動時在我的TableView(類UITableViewController)中顯示警報消息。我在另一個類UIViewController創建了該函數。 這是我的函數:不同類的調用函數

class AlertViewController: UIViewController { 

    func showAlert(titleText: String, messageText: String) { 
     let alertController = UIAlertController(title: titleText, message: messageText, preferredStyle: .alert) 
     self.present(alertController, animated: true, completion: nil) 
     let okAction = UIAlertAction(title: "Ok", style: .default) { (action: UIAlertAction) in } 
     let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (action: UIAlertAction) in } 

     alertController.addAction(okAction) 
     alertController.addAction(cancelAction) 
    } 
} 

然後我調用這個函數在其他類:

class NewTableViewController: UITableViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let new = AlertViewController() 
     new.showAlert(titleText: "How is going?", messageText: "Have a nice day!") 

,但是當我開始我的應用程序,此警報消息不會出現。 我該如何解決這個問題?非常感謝您的幫助! }

回答

0

要顯示警報,您需要創建兩個控制器。首先是AlertViewController,然後是UIAlertController。您試圖從AlertViewController的實例中顯示UIAlertController,但該控制器未顯示!我們將全部刪除AlertViewController。相反,我們將使用的擴展,我們將展示從控制器,實際上是顯示警告:

extension UIViewController { 

    func showAlert(titleText: String, messageText: String) { 
     let alertController = UIAlertController(title: titleText, message: messageText, preferredStyle: .alert) 

     let okAction = UIAlertAction(title: "Ok", style: .default) { (action: UIAlertAction) in } 
     let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (action: UIAlertAction) in } 

     alertController.addAction(okAction) 
     alertController.addAction(cancelAction) 

     self.present(alertController, animated: true, completion: nil) 
    } 
} 

古稱

self.showAlert(titleText: "How is going?", messageText: "Have a nice day!") 
+0

太好了,謝謝! – Stas