当您使用 AttributedString 单击 href 时是否可以使 UILabel 可单击
Is it possible to make UILable clickable when you click on href using AttributedString
我已成功将 HTML
显示为 UILable 中的属性字符串。
问题是当 HtmlString 包含 href link
当你像屏幕截图那样点击那个 href 时没有任何反应。
html 字符串示例
"The Privacy Policy can be found <a href=\"https://www.w3schools.com/python/python_for_loops.asp\">here</a> "
我的代码
let stringHTMl = "The Privacy Policy can be found <a href=\"https://www.w3schools.com/python/python_for_loops.asp\">here</a> "
cell.textUILable.attributedText = stringHTMl.convertHtml()
转换 stringToattributesHTMLString 的扩展
func convertHtml() -> NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
您可以使用 UITextView
。 UITextView
here.
的解决方案
此外,您可以添加 textView.isEditable = false
看起来像 UILabel
。
Swift 4.0 或最新版本
你可以这样实现:
let tapAction = UITapGestureRecognizer(target: self, action:@selector(actionTapped(_:)))
cell.textUILable.isUserInteractionEnabled = true
cell.textUILable.addGestureRecognizer(tapAction)
点击的动作定义为
func actionTapped(_ sender: UITapGestureRecognizer) {
// on tap text Label code here what you want to do
}
在actionTapped
中做任何想做的事
我已成功将 HTML
显示为 UILable 中的属性字符串。
问题是当 HtmlString 包含 href link
当你像屏幕截图那样点击那个 href 时没有任何反应。
html 字符串示例
"The Privacy Policy can be found <a href=\"https://www.w3schools.com/python/python_for_loops.asp\">here</a> "
我的代码
let stringHTMl = "The Privacy Policy can be found <a href=\"https://www.w3schools.com/python/python_for_loops.asp\">here</a> "
cell.textUILable.attributedText = stringHTMl.convertHtml()
转换 stringToattributesHTMLString 的扩展
func convertHtml() -> NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
您可以使用 UITextView
。 UITextView
here.
此外,您可以添加 textView.isEditable = false
看起来像 UILabel
。
Swift 4.0 或最新版本
你可以这样实现:
let tapAction = UITapGestureRecognizer(target: self, action:@selector(actionTapped(_:)))
cell.textUILable.isUserInteractionEnabled = true
cell.textUILable.addGestureRecognizer(tapAction)
点击的动作定义为
func actionTapped(_ sender: UITapGestureRecognizer) {
// on tap text Label code here what you want to do
}
在actionTapped