我想在我的应用程序启动时在我的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 :(得分:0)
要显示警报,您将创建两个控制器。首先是AlertViewController
,然后是UIAlertController
。您正试图从UIAlertController
的实例中显示AlertViewController
,但该控制器未显示!
要解决此问题,我们会完全删除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!")