更改消息UIAlertController swift

更改消息UIAlertController swift,swift,Swift,我做了一个计数器应用程序,在不同的情况下,我有许多错误消息。 我想知道是否可以只更改警报的消息,因为只有一个警报 ''' } ''' 感谢您的帮助SWIFT 5 对UIAlertController进行如下扩展: import UIKit extension UIAlertController { class func showAlertWithOK(viewController: UIViewController, alertTitle: String, message: Strin

我做了一个计数器应用程序,在不同的情况下,我有许多错误消息。 我想知道是否可以只更改警报的消息,因为只有一个警报

'''

}

'''


感谢您的帮助

SWIFT 5

对UIAlertController进行如下扩展:

import UIKit

extension UIAlertController {
    class func showAlertWithOK(viewController: UIViewController, alertTitle: String, message: String) {
        let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .cancel))
        viewController.present(alert, animated: true)
    }
}
UIAlertController.showAlertWithOK(viewController: self, alertTitle: "Your title", message: "your message")
您可以这样使用它:

import UIKit

extension UIAlertController {
    class func showAlertWithOK(viewController: UIViewController, alertTitle: String, message: String) {
        let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .cancel))
        viewController.present(alert, animated: true)
    }
}
UIAlertController.showAlertWithOK(viewController: self, alertTitle: "Your title", message: "your message")

创建一个类似于以下内容的惰性变量

lazy var alertViewController: UIAlertController = {
    let alertViewController = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
    alertViewController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
    return alertViewController
}()
然后在方法内部,在显示之前更改警报的
标题
消息
属性

@objc func displayError(){
    alertViewController.title = "Your title here"
    alertViewController.message = "Your message here"
    self.present(alertViewController, animated: true, completion: nil)
}
对于更一般的情况,您可以使用相同的方便扩展

extension UIViewController {
    func alert(title: String, message: String? = nil, action: (() -> ())? = nil) {
       let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
       let action = UIAlertAction(title: "OK", style: .default) { (UIAlertAction) in
        action?()
       }
       alertController.addAction(action)
       self.present(alertController, animated: true, completion: nil)
    }
}