How to display HTML with DTCoreText in UITextView/UILabel with custom color, font, etc. in iOS using Swift
- July 10, 2019
- John Codeos
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'
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
Now we will use a UIView and use the custom class DTAttributedLabel instead of UILabel
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.
After that, add it to your ViewController.swift file by pressing Control + dragging the UIView to your file, and name it.
For UILabel you need to use DTAttributedLabel and DTAttributedTextView for UITextView.
Here we’re going to use DTAttributedLabel.
Add the following code:
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
..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!