1

I have a UILabel. And I want to set a string that also contains some HTML tags in it. The string is:

NSString *str = @"<p>Hey you. My <b>name </b> is <h1> Joe </h1></p>";

How can i display this on the UILabel

NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];



    mylabel.attributedText=attrStr;

The above code doesn't display anything.

Illep
  • 16,375
  • 46
  • 171
  • 302
  • http://stackoverflow.com/questions/4789447/write-html-content-to-nsstring-and-display-on-iphone . Hope will helpful to you. – Meera Oct 23 '15 at 11:41
  • Doesn't display anything? Is `attrStr` nil? What about using `error` parameter? Is `myLabel` nil? – Larme Oct 23 '15 at 12:25
  • if `UILabel` doesn't work in your case then why don't you use `UIWebView` which is made for it? Just disable the scrolling. – TheTiger Mar 21 '16 at 05:17
  • Possible duplicate of [UILabel text as html text](http://stackoverflow.com/questions/5743844/uilabel-text-as-html-text) – Adela Toderici Mar 20 '17 at 11:10

2 Answers2

5

For iOS7 or more you can use this:

NSString * htmlString = @" <p><b>Hey</b> you. My <b>name </b> is <h1> Joe </h1></p> ";
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];


UILabel * myLabel = [UILabel alloc] init];
myLabel.attributedText = attrStr;

Its works

Mahesh
  • 956
  • 10
  • 17
  • There's a similar answer on http://stackoverflow.com/questions/19946251/how-to-show-an-html-string-on-a-uilabel-in-ios But, it doesn;t work – Illep Oct 23 '15 at 11:37
  • I recently test it on ios 8.4 and then post a comment if you want screen shot then check it below link https://www.dropbox.com/s/jfu029l3g7z64cm/Screen%20Shot%202015-10-23%20at%205.08.54%20pm.png?dl=0 – Mahesh Oct 23 '15 at 11:43
  • I didn't test with uilabel, I'm certainly sure it works with regard to UITextView – kokos8998 Oct 23 '15 at 11:43
2

You should used following code. it's help you!! Apple provided document and link for NSAttributedString.

https://developer.apple.com/documentation/foundation/nsattributedstring/1524613-initwithdata

NSString * htmlString = @"You added a note - in <a href='http://localhost:80/ABC/phase2/public/users/Test/notes/5'>hfgh</a>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
myLabel.attributedText = attrStr;
BuLB JoBs
  • 841
  • 4
  • 20