0

So I am trying to get the following code to work

     return try NSAttributedString(data: data, attributes:[ NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0) ], options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)

I have tried the following too but just fails

extension String {
    var htmlToAttributedString: NSAttributedString? {

        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
               let font = UIFont.systemFont(ofSize: 72)
               let attributes = [NSAttributedString.Key.font: font]
            return try NSAttributedString(data: data,  attributes: attributes, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}
RussellHarrower
  • 6,470
  • 21
  • 102
  • 204
  • You convert first into NSAttributedString the HTML code, then you add a font, or you add a HTML tag for that before. – Larme Dec 11 '19 at 19:58
  • @Larme the html is only

    tags and tags nothing more

    – RussellHarrower Dec 12 '19 at 01:02
  • https://stackoverflow.com/questions/19921972/parsing-html-into-nsattributedtext-how-to-set-font https://stackoverflow.com/a/41413014/1801544 etc. – Larme Dec 12 '19 at 09:17
  • Does this answer your question? [Swift- Change font on an HTML string that has its own Styles](https://stackoverflow.com/questions/41412963/swift-change-font-on-an-html-string-that-has-its-own-styles) – Larme Dec 12 '19 at 09:17

1 Answers1

1

You are convert html to NSAttributedString? You can append style to the string source.

example: https://stackoverflow.com/a/41519178/4368670

extension String {
    func htmlToAttributedString(fontName: String = "Chalkduster", fontSize: Float = 72) -> NSAttributedString? {
        let style = "<style>body { font-family: '\(fontName)'; font-size:\(fontSize)px; }</style>"
        guard let data = (self + style).data(using: .utf8) else {
            return nil
        }
        return try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
    }
}
let html = "<div>content</div>"
lebal.attributedText = html.htmlToAttributedString()

result:

result

zhaozq
  • 51
  • 4