Swift:在标签或textView中显示HTML数据

Tal*_*han 59 html uitextview nsattributedstring ios swift

我有一些HTML数据,其中包含标题,段落,图像和列表标签.

有没有办法在一个UITextView或中显示这些数据UILabel

小智 151

对于Swift 4:

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,只要您想将HTML文本放在UITextView中使用:

textView.attributedText = htmlText.htmlToAttributedString
Run Code Online (Sandbox Code Playgroud)

  • 这应该保留图像吗? (4认同)
  • 这对我很有用,但我不得不使用label.attributedText. (3认同)
  • 似乎加载速度非常慢 (2认同)
  • @Roger Carvalho:有没有办法为包含的html标签设置font-family、-size等? (2认同)
  • @MartinzChukz 在选项 `.characterEncoding: String.Encoding.utf8.rawValue` 中添加此内容 (2认同)

gar*_*rie 34

这是一个Swift 3版本:

private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private 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: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch {
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

我在这里找到了一些其他答案的问题,我花了一些时间来做到这一点.我设置换行模式和行数,以便在HTML跨越多行时标签大小适当.

  • 如何添加自定义字体? (2认同)

Him*_*shu 13

添加此扩展名以将您的html代码转换为常规字符串:

    extension String {

        var html2AttributedString: NSAttributedString? {
            guard
                let data = dataUsingEncoding(NSUTF8StringEncoding)
            else { return nil }
            do {
                return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
            } catch let error as NSError {
                print(error.localizedDescription)
                return  nil
            }
        }
        var html2String: String {
            return html2AttributedString?.string ?? ""
        }
}
Run Code Online (Sandbox Code Playgroud)

然后在UITextView或UILabel中显示您的String

textView.text = yourString.html2String 要么

label.text = yourString.html2String
Run Code Online (Sandbox Code Playgroud)

  • 是的,但它仅适用于 HTML 中的文本。我还担心图像和列表。有什么方法可以显示图像和列表是单个对象吗? (2认同)

Ved*_*yar 7

Swift 3.0

var attrStr = try! NSAttributedString(
        data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)
label.attributedText = attrStr
Run Code Online (Sandbox Code Playgroud)


小智 7

此后,我在更改文本属性时遇到问题,我可以看到其他人问为什么...

因此,最佳答案是将扩展名与NSMutableAttributedString结合使用:

extension String {

 var htmlToAttributedString: NSMutableAttributedString? {
    guard let data = data(using: .utf8) else { return nil }
    do {
        return try NSMutableAttributedString(data: data,
                                      options: [.documentType: NSMutableAttributedString.DocumentType.html,
                                                .characterEncoding: String.Encoding.utf8.rawValue],
                                      documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
 }

}
Run Code Online (Sandbox Code Playgroud)

然后您可以通过以下方式使用它:

if let labelTextFormatted = text.htmlToAttributedString {
                let textAttributes = [
                    NSAttributedStringKey.foregroundColor: UIColor.white,
                    NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 13)
                    ] as [NSAttributedStringKey: Any]
                labelTextFormatted.addAttributes(textAttributes, range: NSRange(location: 0, length: labelTextFormatted.length))
                self.contentText.attributedText = labelTextFormatted
            }
Run Code Online (Sandbox Code Playgroud)


Zgp*_*ace 7

对于 Swift 5,它还可以加载 css。

extension String {
    public var convertHtmlToNSAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else {
            return nil
        }
        do {
            return try NSAttributedString(data: data,options: [.documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }
        catch {
            print(error.localizedDescription)
            return nil
        }
    }

    public func convertHtmlToAttributedStringWithCSS(font: UIFont? , csscolor: String , lineheight: Int, csstextalign: String) -> NSAttributedString? {
        guard let font = font else {
            return convertHtmlToNSAttributedString
        }
        let modifiedString = "<style>body{font-family: '\(font.fontName)'; font-size:\(font.pointSize)px; color: \(csscolor); line-height: \(lineheight)px; text-align: \(csstextalign); }</style>\(self)";
        guard let data = modifiedString.data(using: .utf8) else {
            return nil
        }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }
        catch {
            print(error)
            return nil
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

之后,转到要转换为 NSAttributedString 的字符串并将其放置如下示例:

myUILabel.attributedText = "Swift is awesome&#33;&#33;&#33;".convertHtmlToAttributedStringWithCSS(font: UIFont(name: "Arial", size: 16), csscolor: "black", lineheight: 5, csstextalign: "center")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 以下是每个参数的要求:

  • 字体:像往常一样在 UILabel/UITextView 中添加字体,使用 UIFont 和自定义字体的名称和大小。
  • csscolor:以十六进制格式添加颜色,如“#000000”或使用颜色名称,如“黑色”。
  • lineheight:当你在 UILabel/UITextView 中有多行时,它是行之间的空间。
  • csstextalign:就是文字的对齐方式,需要加的值是“left”或“right”或“center”或“justify”

参考:https : //johncodeos.com/how-to-display-html-in-uitextview-uilabel-with-custom-color-font-etc-in-ios-using-swift/


Nik*_*nko 6

我正在使用这个:

extension UILabel {
    func setHTML(html: String) {
        do {
            let attributedString: NSAttributedString = try NSAttributedString(data: html.data(using: .utf8)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
            self.attributedText = attributedString
        } catch {
            self.text = html
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


osc*_*arr 6

斯威夫特 5

extension UIColor {
    var hexString: String {
        let components = cgColor.components
        let r: CGFloat = components?[0] ?? 0.0
        let g: CGFloat = components?[1] ?? 0.0
        let b: CGFloat = components?[2] ?? 0.0

        let hexString = String(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)),
                               lroundf(Float(b * 255)))

        return hexString
    }
}
Run Code Online (Sandbox Code Playgroud)
extension String {
    func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
        do {
            let htmlCSSString = "<style>" +
                "html *" +
                "{" +
                "font-size: \(size)pt !important;" +
                "color: #\(color.hexString) !important;" +
                "font-family: \(family ?? "Helvetica"), Helvetica !important;" +
            "}</style> \(self)"

            guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                return nil
            }

            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            print("error: ", error)
            return nil
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后你可以创建 UILabel:

func createHtmlLabel(with html: String) -> UILabel {
    let htmlMock = """
    <b>hello</b>, <i>world</i>
    """

    let descriprionLabel = UILabel()
    descriprionLabel.attributedText = htmlMock.htmlAttributed(family: "YourFontFamily", size: 15, color: .red)

    return descriprionLabel
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明

见教程:

https://medium.com/@valv0/a-swift-extension-for-string-and-html-8cfb7477a510


Ale*_*rel 5

雨燕3

extension String {


var html2AttributedString: NSAttributedString? {
    guard
        let data = data(using: String.Encoding.utf8)
        else { return nil }
    do {
        return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil)
    } catch let error as NSError {
        print(error.localizedDescription)
        return  nil
    }
}
var html2String: String {
    return html2AttributedString?.string ?? ""
 }
}
Run Code Online (Sandbox Code Playgroud)