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 ?? ""
    }
}
4

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

that did not help
Hi @zhaozq, I am a bit suprised that this is how people are doing this, I would of thought that Apple would of alllowed font re-sizing natively instead of having a complete html style tag
i think it's difficult to find a range to resize, but using html style tag is easy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.