好吧,正如 rmaddy 所建议的,我已经使用 ViewController 创建了一个自定义警报。
我在 StoryBoard 中添加了一个 ViewController,不透明度为 75%。在其上方,一个带有两个标签(警报和消息)和一个按钮(用于关闭整个事物)的视图。在关联的类中,唯一的代码是:
var alertTitle: String?
var messageContent: String?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var AlertView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
AlertView.layer.cornerRadius = 5.0
let attrStr = try! NSAttributedString(
data: (messageContent?.data(using: String.Encoding.unicode, allowLossyConversion: true)!)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
titleLabel.text = alertTitle
messageLabel.lineBreakMode = .byWordWrapping
messageLabel.numberOfLines = 0
messageLabel.attributedText = attrStr
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func closeButtonTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
基本上,这将接收将显示为标题的文本和消息(将是 HTML)。
为了使用那个 ViewController,我用这段代码创建了一个函数:
func createAlert(title: String, message: String) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let alert = storyBoard.instantiateViewController(withIdentifier: "alert") as! AlertViewController
alert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
alert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
alert.alertTitle = title
alert.messageContent = message
self.present(alert, animated: true, completion: nil)
}
据我所知,它有效。消息看起来像没有样式的纯 HTML 文本(所以我需要更正它),但它可以满足我的需要。
iOS 上的警报无法显示 HTML 内容,这有点奇怪。我认为这可能是一个不错的功能。无论如何,感谢 rmaddy 的建议。这比我预期的要容易。