我有一个包含 HTML
代码的字符串。显示它的最佳方式是什么(它包含图像),我还想在那个可点击的链接中创建链接(在 Safari
中打开)
我尝试了字符串扩展,从 HTML
中给我 NSAttributedString
,但图像只显示了一部分,链接不可点击。
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
}
}
它向我显示了 UILabel
中的 HTML
,但我无法点击链接,并且图像会根据设备宽度进行裁剪。
最佳答案
我认为最好的选择是将此 html 字符串保存为文件,然后使用 Web View 加载此文件。 检查这个question
关于html - 如何显示来自 HTML 字符串的链接和图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56898051/