我正在我的表格 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
}
我在 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/