D. Finna
D. Finna

Reputation: 467

NSAttributedString won't show correct font

I have a label showing HTML through this NSAttributedString function. The problem is that I want to add a custom font to it, but it does not add the font.

What have I done wrong?

Here is my code:

extension String {
    func convertHtml() -> NSAttributedString {
        let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]

        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.init(string: self, attributes: titleAttributes)
        }
    }
}

Upvotes: 0

Views: 283

Answers (1)

rmaddy
rmaddy

Reputation: 318774

If you wish to replace all font settings from the resulting HTML, you need to apply your titleAttributes after creating the attributed string from the HTML string.

extension String {
    func convertHtml() -> NSAttributedString {
        let titleAttributes = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline), NSAttributedStringKey.foregroundColor: UIColor.black]

        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do{
            let res = try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
            let mutable = res.mutableCopy() as! NSMutableAttributedString
            mutable.addAttributes(titleAttributes, range: NSRange(location: 0, length: res.length))

            return mutable
        }catch{
            return NSAttributedString.init(string: self, attributes: titleAttributes)
        }
    }
}

Upvotes: 2

Related Questions