Skip to content

Instantly share code, notes, and snippets.

@startupcode
Last active October 3, 2023 01:08
Show Gist options
  • 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
}
@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