58

I am getting a title in HTML format as

<p><span style="color: #000000;"><strong>Example </strong></span></p>

I need to show this HTML string in a UILabel. The color code and the font size should be same as the coming in HTML. When I am converting the HTML string into a NSString, only the text "Example" is coming, and not the color.

Is there any solution?

Thnx in advance

Till now I am trying by using a NSAttributedString in following way but by this way the whole HTML is printing:

UIFont *font = [UIFont systemFontOfSize:14.0];
UIFont *secondFont = [UIFont systemFontOfSize:10.0];

NSMutableDictionary *firstAttributes;
NSMutableDictionary *secondAttributes;

NSDictionary *firstAttributeFont = @{NSFontAttributeName:font};
NSDictionary *secondAttributeFont = @{NSFontAttributeName:secondFont};

[firstAttributes addEntriesFromDictionary:firstAttributeFont];
[secondAttributes addEntriesFromDictionary:secondAttributeFont];

[firstAttributes addEntriesFromDictionary:@{NSForegroundColorAttributeName:[UIColor clearColor]}];
[secondAttributes addEntriesFromDictionary:@{NSForegroundColorAttributeName:[UIColor clearColor]}];



NSString* completeString = [NSString stringWithFormat:@"%@",strTitle];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]     initWithString:completeString];
[attributedString setAttributes:firstAttributes range:[completeString rangeOfString:strTitle]];
//   [attributedString setAttributes:secondAttributes range:[completeString rangeOfString:self.secondAttributeText]];
Cell.lbl_Title.attributedText = attributedString;

7 Answers 7

130

For iOS7 or more you can use this:

NSString * htmlString = @"<html><body> Some html string </body></html>";
NSAttributedString * attrStr = 
  [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] 
                                   options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
                        documentAttributes:nil error:nil];

UILabel * myLabel = [[UILabel alloc] init];
myLabel.attributedText = attrStr;
7
  • 3
    It works, but how can I catch a "touch" event on the UILabel?
    – lenhhoxung
    Commented May 3, 2015 at 12:45
  • @lenhhoxung my advice for u, try to use UIButton instead of UILabel or add UIButton above your label, it's kinda easy way to achieve what you want.
    – Resty
    Commented May 21, 2015 at 19:27
  • 2
    Thanks, but I just want to catch "touch" event on the link inside html content, not all the label
    – lenhhoxung
    Commented May 21, 2015 at 20:56
  • @Nilesh Can you please post your code? If it works for everyone but for you..there might be something wrong with your code.
    – sanjana
    Commented Aug 12, 2015 at 5:15
  • 1
    @lenhhoxung I wasn't looking for an answer for this question. I wanted clickable links. Replaced UILabel with UITextView. Works like a charm :)
    – A_G
    Commented Jul 6, 2017 at 13:14
29

Swift 2

let htmlText = "<p>etc</p>"

if let htmlData = htmlText.dataUsingEncoding(NSUnicodeStringEncoding) {
    do {
        someLabel.attributedText = try NSAttributedString(data: htmlData,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)
    } catch let e as NSError {
        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
    }
}

Swift 3

let htmlText = "<p>etc</p>"

if let htmlData = htmlText.data(using: String.Encoding.unicode) {
    do {
        let attributedText = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    } catch let e as NSError {
        print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
    }
}
4
  • 1
    just added Swift 3 into your "Swift troll translation" ;) it was quite handy to find it.
    – Michal
    Commented Nov 14, 2016 at 14:53
  • <a> tags are highlighted but don't work. Any idea how to get it to work? Commented Apr 4, 2017 at 15:00
  • UILabels are not meant to be interactive at all. Look into UITextField stackoverflow.com/questions/21629784/…
    – BaseZen
    Commented Apr 4, 2017 at 16:12
  • 3
    Does not work in Swift 4 Cannot convert value of type 'NSAttributedString.DocumentAttributeKey' to expected dictionary key type 'NSAttributedString.DocumentReadingOptionKey' Commented Jan 14, 2018 at 9:28
21

Swift 4+

For Swift 4 and above use:

guard let data = "foo".data(using: String.Encoding.unicode) else { return }

try? titleLabel.attributedText = 
   NSAttributedString(data: data,
                   options: [.documentType:NSAttributedString.DocumentType.html], 
        documentAttributes: nil)
1
  • its making uitableview to stuck on scroll , even if I tried on thread Commented Aug 1, 2018 at 11:05
6

I did this on UITextView as follows:

[detailView loadHTMLString:[NSString stringWithFormat:@"<div style='text-align:justify; font-size:13px;font-family:HelveticaNeue;color:#362932;'>%@",[model.dict valueForKey:@"description"]] baseURL:nil];

Or you can use RTLabel library: https://github.com/honcheng/RTLabel to display html text along with its formatting on a label.

1
  • 6
    Don't use loadHTMLString, it's a private api.
    – Beuj
    Commented Jan 10, 2014 at 15:54
5

Extension for Swift 4+

extension UILabel {
  func set(html: String) {
    if let htmlData = html.data(using: .unicode) {
      do {
        self.attributedText = try NSAttributedString(data: htmlData,
                                                     options: [.documentType: NSAttributedString.DocumentType.html],
                                                     documentAttributes: nil)
      } catch let e as NSError {
        print("Couldn't parse \(html): \(e.localizedDescription)")
      }
    }
  }
}
3
  • I don't know why it takes little longer time (approx. 3 to 5 sec) to load initially?
    – iAj
    Commented Aug 5, 2017 at 10:40
  • 1
    @iajmeri43 See this answer. Commented Aug 5, 2017 at 10:44
  • Got it... tnx alot.. @Orkhan Alikhanov
    – iAj
    Commented Aug 5, 2017 at 10:48
4
-(NSString*)convertHtmlPlainText:(NSString*)HTMLString{
    NSData *HTMLData = [HTMLString dataUsingEncoding:NSUTF8StringEncoding];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:HTMLData options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:NULL error:NULL];
    NSString *plainString = attrString.string;

    return plainString;
}

UILabel * htmlLabel = [UILabel alloc] init];
htmlLabel.text = [self convertHtmlPlainText:htmlResponse];
1
  • attributedStringWithHTML does not exist. attrString declaration/init should be replaced by: NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:HTMLData options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:NULL error:NULL];
    – atxe
    Commented Dec 23, 2014 at 16:46
0

If Html Text is like

var planeText = "Unseen and not Purchased!"
//setting color to the text
var htmlText = "<font color=\"#f20707\">" + planeText + "</font>"  

We can set the text to UILabel like this

if let htmlData = htmlText.data(using: String.Encoding.unicode) {
    do {
         let attributedText = try NSAttributedString(data: htmlData,
             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
             documentAttributes: nil)   
         //Setting htmltext to uilable 
         uilable.attributedText = attributedText

       } catch let e as NSError {
         //setting plane text to uilable cause of err
         uilable.text = planeText
         print("Couldn't translate \(htmlText): \(e.localizedDescription) ")
       }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.