Member-only story
HTML text in UILabel iOS
1 min readOct 3, 2020
Sometimes we need to display HTML content on the screen by using UILabel. How to display the HTML content in UILabel we see that in this article. let’s start and achieve it.
Objective C:
NSString * htmlString = @"<html><body> <b> HTML in UILabel is here…. </b> </body></html>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString
dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute:
NSHTMLTextDocumentType } documentAttributes:nil error:nil];UILabel * yourLabel = [[UILabel alloc] init];
yourLabel.attributedText = attrStr;
Swift:
var htmlString = “<html><body> <b> HTML in UILabel is here…. </b> </body></html>”
var attrStr: NSAttributedString? = nil
do {
if let data = htmlString.data(using: .unicode) {
attrStr = try NSAttributedString(data: data, options: [
NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html.rawValue
], documentAttributes: nil)
}
} catch {
}
var yourLabel = UILabel()
yourLabel.attributedText = attrStr