ios - 打开设置为 UILabel 作为属性字符串的文本上的链接。从 json 响应中读取属性字符串

标签 ios swift uilabel nsattributedstring urlspan

我正在我的表格 View 单元格中读取此 json 响应。我已将其设置为 UILabel 并设法将其显示为归因于我的标签。我的 View 将标签内的文本显示为链接,但单击链接不起作用。 我想要的是点击这些链接打开浏览器。

{"Disclaimer":"I have read & accept the <a href=\"https:\/\/staging.rentalcover.com\/pds\/W80P-J8ZP-INS\" target=\"_blank\">Policy Terms<\/a>. I have read & accept the <a href=\"https:\/\/staging.rentalcover.com\/pds\/W80P-J8ZP-INS\">Policy Terms<\/a>. This policy is issued by RentalCover.com, AFSL No.490058 and underwritten by Assetinsure Pty Ltd."}

下面是我的代码

var htmlResponse:String = obj.Disclaimer ?? ""
let myText = htmlResponse
lbl_Disclaimer.attributedText = self.stringFromHtml(string: myText)
lbl_Disclaimer.font = UIFont(name: "Poppins-Regular", size: 13)

// MARK:- HTML TO STRING
func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSAttributedString.DocumentReadingOptionKey.documentType:  NSAttributedString.DocumentType.html],
                                             documentAttributes: nil)
            return str
        }
    } catch {
    }
    return nil
}

文本在我的应用程序中显示方式的图像。 enter image description here

我在 json 响应中获取文本“政策条款”的链接,并希望可以单击它以在浏览器中打开该链接。

谢谢

最佳答案

使用 UIWebView 来实现这一点。在 UIlable 上,您可以分配 AttributedText,但无法确定从文本中点击了哪个特定单词。因此,放置一个 UIWebView 并调用 loadHTMLString("<HTML>some string </HTML>")方法。 实现委托(delegate)方法StartLoadRequest .

请使用以下代码:-

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        guard let url = request.url else{
            return false
        }
        if "\(url)".contains("http"){
            UIApplication.shared.openURL(request.url!)
        }
        return false
    }

关于ios - 打开设置为 UILabel 作为属性字符串的文本上的链接。从 json 响应中读取属性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57139972/

相关文章:

IOS 内存管理 - 将视频写入临时文件

ios - [NSNull 长度] : unrecognized selector sent to instance 0x37fc8e48 iOS Swift

ios - 使选定的按钮标题标签为大写

objective-c - 如何制作字幕 UILabel/UITextField/NSTextField

ios - UILabel 中不同大小的顶部对齐文本

ios - CNLabel电话号码标签选择器

ios - 错误ITMS-90207:捆绑软件不包含捆绑软件可执行文件

ios - 键盘出现时弹出 View 箭头移动

ios - 当用户导航更深时,UINavigationBar 将变为透明

ios - 使 UILabel 以 45 度角快速交叉背景色