Function 调用不同类中的函数

Function 调用不同类中的函数,function,class,swift3,xcode8,Function,Class,Swift3,Xcode8,我想在我的应用程序启动时在我的TableView(UITableViewController类)上显示警报消息。我在另一个类UIViewController中创建了该函数。 这是我的职责: class AlertViewController: UIViewController { func showAlert(titleText: String, messageText: String) { let alertController = UIAlertController(

我想在我的应用程序启动时在我的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!")
但当我启动应用程序时,此警报消息不会出现。
我怎样才能解决这个问题??非常感谢你的帮助!!}

要显示警报,您需要创建两个控制器。首先是
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!")

太好了,谢谢!!