How to display HTML in UITextView/UILabel with custom color, font, etc. in iOS using Swift

How to display HTML in UITextView/UILabel with custom color, font, etc. in iOS using Swift

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 "black".
  • 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 "left" or "right" or "center" or "justify"

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Gisela Recent comment authors
newest oldest most voted
Notify of

Hi! This helped a lot! I have a question, is there a way to convert a css file into inline style and inject it into a html file in order to use this method?

Thank you very much!

Follow me