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)

import DTCoreText
extension String {
//Use of DTCoreText library to convert html to String.
public func returnAttributedStringForHTMLString (fontFamily: String, fontName: String, fontSize: CGFloat, textColor: UIColor, textAlignment: CTTextAlignment) -> NSMutableAttributedString {
let encodedData = self.data(using: String.Encoding.utf8)!
let options = [
DTDefaultFontFamily:fontFamily,
DTDefaultFontName: fontName,
DTDefaultFontSize: fontSize,
DTDefaultTextColor: textColor,
DTDefaultTextAlignment: NSNumber(value: textAlignment.rawValue)
] as [String : Any]
let builder = DTHTMLAttributedStringBuilder(html: encodedData, options: options, documentAttributes: nil)
var returnValue:NSAttributedString?
returnValue = builder?.generatedAttributedString()
if returnValue != nil {
//needed to show link highlighting
let mutable = NSMutableAttributedString(attributedString: returnValue!)
mutable.removeAttribute(NSAttributedString.Key.foregroundColor, range: NSMakeRange(0, mutable.length))
return mutable
}else{
return NSMutableAttributedString(string: "")
}
}
}
view raw Extensions.swift hosted with ❤ by GitHub

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:

let exampleLabel = DTAttributedLabel()
self.view.addSubview(exampleLabel)
exampleLabel.backgroundColor = UIColor.groupTableViewBackground
exampleLabel.attributedString = "Swift is awesome!!!".returnAttributedStringForHTMLString(fontFamily: "Helvetica Neue", fontName: "HelveticaNeue-Bold", fontSize: 20, textColor: UIColor.red, textAlignment: .center)
exampleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
exampleLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 20),
exampleLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20),
exampleLabel.heightAnchor.constraint(equalToConstant: 25),
exampleLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
])

Final Step 🎉🎉

Now you can use it like that:

exampleLabel.attributedString = "Swift is awesome!!!".returnAttributedStringForHTMLString(fontFamily: "Helvetica Neue", fontName: "HelveticaNeue-Bold", fontSize: 20, textColor: UIColor.red, textAlignment: .center)
view raw example.swift hosted with ❤ by GitHub

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

avatar
  Subscribe  
Notify of

Stay Connected

Newsletter

Subcribe for weekly emails! Get my posts of the week right in your inbox!