我的UIAlertController正在显示所有HTML格式,但链接不可点击。这里的帖子假定我们知道链接的位置,但是文本消息来自API,因此我无法控制特定的字符串。我希望有一个可以分配给UIAlertController的通用属性,以便链接变得可点击。感谢
let htmlText = "Some text from API with random links here and there"
let alertController = UIAlertController(title: "Details", message:"", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
let attributedText = htmlText.html2AttributedString
alertController.setValue(attributedText, forKey: "attributedTitle")
字符串扩展 html2AttributedString 此处,但此扩展程序正在运行,因此无需检查此部分:
extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8),
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
}
答案 0 :(得分:0)
以标准方式无法实现,因为您无权访问UILabel
内部的UIAlertController
在普通的UILabel
中,您可以在UILabel
上添加轻击手势并进行处理。
所以在这里你需要一个自定义的UIAlertController
但是我建议您从html文本中导出链接,并将其显示为如下所示的操作按钮:
var links : [String:NSURL] = [:]
let range = NSMakeRange(0, attributedText.length)
attributedText.enumerateAttribute(.link, in: range, options: .longestEffectiveRangeNotRequired) {attribute, range, pointer in
let text = attributedText.attributedSubstring(from: range).string
if let url = attribute as? NSURL {
links[text] = url
}
}
links.forEach { (linkText, url) in
alertController.addAction(UIAlertAction(title: linkText, style: .default, handler: {_ in
UIApplication.shared.openURL(url as URL)
}))
}