【问题标题】:Convert HTML string to plain string Objective-C将 HTML 字符串转换为纯字符串 Objective-C
【发布时间】:2015-10-27 09:23:59
【问题描述】:

我创建了一个UITableView,每个单元格都包含一个UILabel。输入是一些 HTML 字符串(如网站页面源),例如来自 Example Domain:

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is established to be used for illustrative examples in documents. You may use this
    domain in examples without prior coordination or asking for permission.</p>
    <p><a href="http://www.iana.org/domains/example">More information...</a></p>
</div>
</body>

但要大得多,超过 4000 个字符。

我想将这些 HTML 字符串转换为纯字符串,例如上面的例子:

示例域

此域的建立是为了用于文档中的说明性示例。您可以在没有事先说明的情况下在示例中使用此域 协调或请求许可。

更多信息...

然后在UILabel 中显示它们。目前我正在使用这种方式:

NSData *htmlData = [htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSAttributedString *attrString = [[NSAttributedString alloc]
          initWithData:HTMLData
               options:@{
                   NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType
               }
    documentAttributes:nil
                 error:nil];
NSString *plainString = attrString.string;

这工作正常,但性能很差,导致滚动tableView时闪烁。有没有更有效的方法来做到这一点?

【问题讨论】:

  • 在重新加载 tableview 之前缓存字符串怎么样?您可以在后台线程中生成字符串,然后重用它们
  • 谢谢,这是一个好方法,但是我对 tableview 的输入非常复杂,所以我更喜欢一种方法来就地转换 html 字符串,而不是解析所有数据并缓存它们。不过我会尝试这样做。
  • 不幸的是,没有办法对每个单元格外观进行高性能处理,因为 html 很复杂,您必须通过文本来转换/替换/删除它的某些部分,如果html 字符串很大,那么问题就更大了,特别是对于旧设备,P.S.其实你上面写的那个函数,在实际设备上比在模拟器上效果更好,你可以自己试试

标签: html ios objective-c plaintext


【解决方案1】:

使用下面的代码:

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

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

【讨论】:

猜你喜欢
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多