当您使用AttributedString单击href时,是否可以使UILable可单击

时间:2019-04-10 14:00:27

标签: ios swift uitextfield

我已成功在UILable中将HTML显示为归因字符串。

问题是,当HtmlString包含href link时,如单击屏幕快照一样单击该href时,什么也没发生。

enter image description here

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()
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用UITextViewUITextView here的解决方案。

此外,您可以将textView.isEditable = false添加为UILabel的样子。

答案 1 :(得分:0)

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

中做您想做的事情