Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show an HTML string on a UILabel in iOS?

Tags:

ios

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; 
like image 267
vasudev Avatar asked Nov 13 '13 05:11

vasudev


People also ask

How do you display HTML formatted text in UILabel Swift?

To render this text properly in UILabel or UITextView, you need to convert it to NSAttributedString . NSAttributedString has built-in support for this conversion. First, we need to convert HTML string to Data . let htmlString = "This is a <b>bold</b> text."


1 Answers

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; 
like image 184
sanjana Avatar answered Sep 21 '22 14:09

sanjana