ios - 显示自定义消息的 Swift UIAlertController

标签 ios swift uialertcontroller

我有一个 ViewController 类,它的唯一目的是显示一 strip 有自定义消息和标题的警报消息,该消息通过自定义初始化消息传入。一旦 View 出现,就会在 viewDidLoad 中完成此操作。然而,我的问题是,当涉及到这个 View 时,它会弹出并永远停留在这个 View 中,而不是仅仅将 View 放在另一个 View 之上。我不确定如何解决这个问题。这是我的 alertVC 类的代码

import UIKit

class AlertVC: UIViewController {

  var myMessage: String?
  var myTitle: String?

  override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }


  override func viewDidAppear(animated: Bool){
    let alertController = UIAlertController(title: myTitle, message: myMessage, preferredStyle: .Alert)
    let OKAction = UIAlertAction(title: "OK", style: .Default) {
        (action: UIAlertAction) in print("Youve pressed OK Button")
    }
    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
  }

  convenience init(title: String, message: String){
    self.init()
    self.myTitle = title
    self.myMessage = message
  }
}

这是我如何为此创建对象并尝试展示它的代码。

let alert = AlertVC(title: "Error", message: "error")
presentViewController(alert, animated: true, completion: nil)

感谢任何帮助,如果您需要更多信息,请发表评论。谢谢!

最佳答案

为什么不只是一个扩展

extension UIViewController {

  func presentAlert(withTitle title: String, message : String) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    let OKAction = UIAlertAction(title: "OK", style: .default) { action in
        print("You've pressed OK Button")
    }
    alertController.addAction(OKAction)
    self.present(alertController, animated: true, completion: nil)
  }
}

并用

调用它
presentAlert(withTitle: "Error", message: "error")

在任何 UIViewController 类中

关于ios - 显示自定义消息的 Swift UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37817702/

相关文章:

ios - 需要帮助了解 << 位运算符在 Objective-C 中的工作原理

json - 从 AWS Lambda 函数解析 JSON 答案

ios - 添加到 Stackview subview 的 CAShapeLayers 仅在一个 subview 上呈现

ios - 我们可以更改 AlertController 按钮字体吗?

objective-c - 为什么我不能禁用ARC(每个文件)?

ios - 架构 armv7 的 undefined symbol : duplicate files

ios - CoreTelephony 因 : Received a notification with no notification name 原因崩溃

swift - UIImageView 不适合我的屏幕

swift - 在 Swift 的自定义单元格中显示操作表

swift - UIAlertController 在某些情况下不会被解雇