【问题标题】:How to show an HTML string on a UILabel如何在 UILabel 上显示 HTML 字符串
【发布时间】:2015-10-23 11:22:53
【问题描述】:

我有一个UILabel。我想设置一个字符串,其中还包含一些HTML 标签。字符串是:

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

如何在UILabel 上显示此内容

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



    mylabel.attributedText=attrStr;

上面的代码没有显示任何内容。

【问题讨论】:

  • stackoverflow.com/questions/4789447/… 。希望对你有所帮助。
  • 什么都不显示? attrStr 是零吗?使用error 参数怎么样? myLabel 是零吗?
  • 如果UILabel 在您的情况下不起作用,那么您为什么不使用专为它设计的UIWebView?只需禁用滚动即可。
  • UILabel text as html text的可能重复

标签: ios objective-c


【解决方案1】:

对于 iOS7 或更高版本,您可以使用这个:

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;

它的作品

【讨论】:

【解决方案2】:

您应该使用以下代码。它对你有帮助! Apple 提供了 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;

【讨论】:

  • 请同时描述您的解决方案,而不仅仅是输入代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-15
  • 2012-03-17
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多