html - 如何显示来自 HTML 字符串的链接和图像

标签 html ios swift

我有一个包含 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/

相关文章:

javascript - 响应式滚动顶部

swift - "implicit conversion from <tuple type> to <tuple type 2> requires a temporary"将元组作为 inout 参数传递时出错

ios - 如何快速获得这个周末约会?

html - 如何让两个并排的 html 输入字段看起来与小于输入字段高度的中间分隔符组合?

应用于正文的 HTML5 全屏 API

iphone - UIImagePickerController 相机不在照片库中保存照片

ios - 无法从格式为 dd-MM-yyyy HH :mm:ss:ms 的字符串中获取日期时间

iphone - 使用 xcode 和 tablecells 登录表单

ios - Swift - NSDateFormater 不工作

javascript - Pycurl 脚本