如何显示HTML字符串中的链接和图像

时间:2019-07-05 07:00:57

标签: html ios swift

我有一个包含HTML代码的字符串。显示该图片(包含图片)的最佳方法是什么,我也想在该可点击对象中创建链接(在Safari中打开)

我尝试过使用NSAttributedString的{​​{1}}字符串扩展名,但是图像仅部分显示,并且无法点击链接。

HTML

它向我显示了let text = htmlString.attributedString(withRegularFont: UIFont.systemFont(ofSize: 14), andBoldFont: UIFont.systemFont(ofSize: 16)) extension String { func attributedString(withRegularFont regularFont: UIFont, andBoldFont boldFont: UIFont, textColor: UIColor = UIColor.gray) -> NSMutableAttributedString { var attributedString = NSMutableAttributedString() guard let data = self.data(using: .utf8) else { return NSMutableAttributedString() } do { attributedString = try NSMutableAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil) let range = NSRange(location: 0, length: attributedString.length) attributedString.enumerateAttribute(NSAttributedString.Key.font, in: range, options: .longestEffectiveRangeNotRequired) { value, range, _ in let currentFont: UIFont = value as! UIFont var replacementFont: UIFont? = nil if currentFont.fontName.contains("bold") || currentFont.fontName.contains("Semibold") { replacementFont = boldFont } else { replacementFont = regularFont } let replacementAttribute = [NSAttributedString.Key.font:replacementFont!, NSAttributedString.Key.foregroundColor: textColor] attributedString.addAttributes(replacementAttribute, range: range) } catch let e { print(e.localizedDescription) } return attributedString } } 内的HTML,但是我无法点击链接,并且图像分别根据设备的宽度进行裁剪。

1 个答案:

答案 0 :(得分:2)

我认为最好的选择是将该html字符串另存为文件,然后使用网络视图加载该文件。 检查此question