我的应用程序中有多个 Controller ,都需要验证,并且验证失败时,我想显示一个带有错误的警报。是否有一些最佳做法/设计模式可以做到这一点?我可以简单地在Helper类中创建一个静态函数,如下所示:

static func displayAlert(message: String, buttonTitle: String, vc: UIViewController)
{
    let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert)

    let okAction = UIAlertAction(title: buttonTitle, style: .Default, handler: nil)
    alertController.addAction(okAction)

    vc.presentViewController(alertController, animated: true, completion: nil)
}

但是然后我需要传递 View Controller ..这似乎是一种不好的做法。我可以发出通知并观察它,但这似乎有些过分。我是不是在考虑这个问题,还是有一些更可接受的方式来处理这样的事情?

最佳答案

我最终为UIViewController创建了一个扩展并在其中创建了警报功能:

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

关于ios - Swift Displaying Alerts最佳做法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29633938/

10-12 00:22
查看更多