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

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

If you don’t want to use a library on your project, then check out the tutorial here. But the performance will be slower than using the DTCoreText library

To display HTML content to UITextView/UILabel we have to convert it to NSAttributedString. So to do this, we are going to use the 3rd party library DTCoreText.

In this tutorial, we will use CocoaPods to install it for our project.

Add the following code to your Podfile and after that run pod update to update the libraries in your pod file.

pod 'DTCoreText', '~> 1.6'

Add DTCoreText to your podfile
Update the pod of the project

To make it simple, I create it an extension so to don’t have to type the same code every time you want to convert something to NSAttributedString.

Open your project and add the following code inside your file with your other Extensions (If you don’t have this file, create a new .swift file and name it Extensions.swift)

Don’t forget to import the library at the top of your file by typing import DTCoreText

Now we will use a UIView and use the custom class DTAttributedLabel instead of UILabel

Storyboard Method

Go to your Storyboard and add a UIView and then add the custom class DTAttributedLabel if you want to use UILabel or DTAttributedTextView for UITextView.

Add a custom class to UIView

After that, add it to your ViewController.swift file by pressing Control + dragging the UIView to your file, and name it.

Control + Drag the UIView to your ViewController.swift file

Programmatically Method

For UILabel you need to use DTAttributedLabel and DTAttributedTextView for UITextView.

Here we’re going to use DTAttributedLabel.

Add the following code:

Final Step

Now you can use it like that:

Here’s what every parameter takes:

  • fontFamily: Add your font’s family name, if the font you use doesn’t have a family name, then type the same name as your font name.
  • fontName: The name of your font you want to use.
  • fontSize: The size of your font.
  • textColor: The color for your text
  • textAlignment: The alignment of your text; it takes the values .left, .right, .center, .justified and .natural

..and here how it looks!

You can find the final project here

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

Leave a Reply

Notify of

Follow me