Skip to content

Instantly share code, notes, and snippets.

@startupcode
Last active October 3, 2023 01:08
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startupcode/fa832a15c6cb38b65f6fb4f74462b819 to your computer and use it in GitHub Desktop.
Save startupcode/fa832a15c6cb38b65f6fb4f74462b819 to your computer and use it in GitHub Desktop.
Swift - Assign HTML to NSAttributedString with custom FONT
//Usage
lbl.attributedText = htmlToAttributedString ("html text")
//Assign attributed string
func htmlToAttributedString(string : String) -> NSAttributedString{
var attribStr = NSMutableAttributedString()
do {//, allowLossyConversion: true
attribStr = try NSMutableAttributedString(data: string.dataUsingEncoding(NSUnicodeStringEncoding)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
let textRangeForFont : NSRange = NSMakeRange(0, attribStr.length)
attribStr.addAttributes([NSFontAttributeName : UIFont(name: "Arial", size:15)!], range: textRangeForFont)
} catch {
print(error)
}
return attribStr
}
@zeeshankhan
Copy link

It does not seem to work.

@hdmdhr
Copy link

hdmdhr commented Jul 29, 2022

It does not seem to work.

The code below worked for me.

First it converts html string to default attributed string; then it enumerates font attribute in the result string, replace the system default font with your custom font; then finally add your new font as a new attribute.

guard let attributedString = try? NSMutableAttributedString(data: Data(htmlString.utf8),
                                                                            options: [.documentType: NSAttributedString.DocumentType.html,
                                                                                      .characterEncoding: String.Encoding.utf8.rawValue],
                                                                            documentAttributes: nil)
                else {
                    return .init(string: "Invalid content")
                }
                
                let range = NSRange(location: 0, length: attributedString.length)
                
                attributedString.enumerateAttribute(.font, in: range) { value, range, pointer in
                    guard let currentFont = value as? UIFont else { return }
                    
                    let isBold = currentFont.fontName.lowercased().contains("bold")
                    let replacementFont = UIFont(name: isBold ? "Arial-Bold" : "Arial", size: currentFont.pointSize)
                    
                    let replacementAttribute = [NSAttributedString.Key.font: replacementFont]
                    attributedString.addAttributes(replacementAttribute, range: range)
                }
                
                return attributedString

@startupcode
Copy link
Author

startupcode commented Jul 30, 2022 via email

@NikKovIos
Copy link

NikKovIos commented Dec 18, 2022

The both of these gists would break markdown. For example monospace and italic text style. This could help, but not working with custom fonts https://stackoverflow.com/a/33828793/5790492

Maybe someone need only to change the size of default font https://stackoverflow.com/a/74841172/5790492

@startupcode
Copy link
Author

startupcode commented Dec 19, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment