How to display HTML in UITextView/UILabel with custom color, font, etc. in iOS using Swift
- July 05, 2019
- John Codeos
If you want to show a list that contains items in HTML in a UITableView or UICollectionView, it’s preferable to use the 3rd party library DTCoreText. It’s a lot of faster that the native way. I have made a tutorial about it, here.
When you want to show a text from HTML content from a website to your app, you have to convert the text to an NSAttributedString format to show it correctly on a UITextView/UILabel.
In this tutorial, I’m gonna saw you how to do this very easily by using an extension that uses custom text color, font and more with the help of CSS.
We’re not going to cover how to add a custom font to your iOS project in this tutorial, but we will focus only on the NSAttributedString implementation.
Just paste the following extension to your Extensions.swift file:
After that, go to your string you want to convert to NSAttributedString and place it like the example below:
Here’s what every parameter takes:
font: Add your font as usually do in a UILabel/UITextView, using UIFont with the name of your custom font and the size.
csscolor: Either add color in HEX format, like
"#000000"or use the name of the color, like
lineheight: It’s the space between the lines when you have multiple lines in a UILabel/UITextView.
csstextalign: It’s the alignment of the text, the value that you need to add is
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!