【问题标题】:iOS html text is not working properly in attributed stringiOS html文本在属性字符串中无法正常工作
【发布时间】:2016-09-21 16:49:55
【问题描述】:

我正在尝试使标签内的部分文本 - 粗体。这是我正在使用的 html 代码:

<style>body{line-height: 0;}</style><font face=\"Calibri\"><b>Get moving!</b> (and Sync to see your points.)</font>

但它使所有文本都变为粗体。如果 HTML 使用 &lt;b&gt;&lt;/b&gt; 标签,情况也是如此。它将使所有文本正常。
似乎它只是开始检查。

谁能帮我解决这个问题?

我使用NSAtributedString 来显示 HTML 文本。想承认它在 HTML 在线编辑器中运行良好。

【问题讨论】:

  • 检查我的回答 Volodymyr

标签: html ios objective-c swift string


【解决方案1】:

我得到了解决方案。我为你的问题尝试了一个示例。我得到了,它工作正常。

NSString *strHTML = @"<style>body{line-height: 0;}</style><font face=\"Calibri\"><b>Get moving!</b> (and Sync to see your points.)</font>";
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[strHTML dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
lblHTMLString.attributedText = attrStr;

输出截图是

【讨论】:

  • 我已经发现了哪里出了问题。它与 HTML 无关。
  • 我的回答是制作正文部分的粗体文本的完美答案。我先检查了 html 在线编辑器。之后只有我尝试过。现在它工作得非常好。
  • 其实并不完美。其原因是因为将 HTML 发布到 NSAttributedString 会导致 WebKit 工作,从而导致 UI 的巨大延迟。只是更容易写,所以我选择它。
  • 如果您被问到“webkit 的 html 字符串或在 webkit 中显示 html 字符串”的问题,我会是第一个给出解决方案的人。但是您要求在标签中显示 html 字符串你的确切输出。
  • 您说这是最好的解决方案。这不是最好的,以前的答案是相同的,我之前评论说它不适合我。
【解决方案2】:

试试这个:

 NSString *description = @"<style>body{line-height: 0;}</style><font face=\"Calibri\"><b>Get moving!</b> (and Sync to see your points.)</font>";
    self.lblDescription.attributedText=[self getData:description];

//Convert HtmlString to string
-(NSAttributedString *)getData:(NSString *)str
{
    NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *options = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType};
    NSAttributedString *decodedString;
    decodedString = [[NSAttributedString alloc] initWithData:stringData
                                                     options:options
                                          documentAttributes:NULL
                                                       error:NULL];
    return decodedString;
}

【讨论】:

  • 已发现问题。它不在 HTML 中。你的代码工作正常。
  • @Volodymyr 请检查截图。它运作良好。
  • 一旦我用屏幕截图发布答案,请勿复制和发布答案。
  • 我没有复制粘贴任何人的截图。我添加该屏幕截图仅作为对 Volodymyr 评论的回复。
猜你喜欢
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
相关资源
最近更新 更多