【问题标题】:How to make NSAttributedString centred align when converting it from HTML string?从 HTML 字符串转换时如何使 NSAttributedString 居中对齐?
【发布时间】:2016-02-23 17:16:31
【问题描述】:

HTML 文本:

<span style="color: rgb(158, 29, 255);"><b>This</b> is a <i>simple</i> <u>text</u>.</span>


输出:

这个是一个简单的 文本。


这是我将 HTML 文本转换为属性字符串的代码:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];
NSAttributedString *attributedString = [[NSAttributedString alloc] 
initWithData:[@"<span style="color: rgb(158, 29, 255);"><b>This</b> is a <i>simple</i> <u>text</u>.</span>" dataUsingEncoding:NSUnicodeStringEncoding]
 options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSParagraphStyleAttributeName:paragraphStyle} 
documentAttributes:nil error:nil];

但是,它没有将属性字符串设置为居中对齐。怎么了?

【问题讨论】:

  • 您不能将NSParagraphStyleAttributeName 与initWithData:options:documentAttributes:error: 一起使用。之后添加。

标签: ios nsattributedstring


【解决方案1】:

根据NSAttributedString的文档:

- (instancetype)initWithData:(NSData *)data
                     options:(NSDictionary<NSString *,
                                      id> *)options
          documentAttributes:(NSDictionary<NSString *,
                                      id> * _Nullable *)dict
                       error:(NSError * _Nullable *)error

选项
用于解释文档内容的文档属性。 NSDocumentTypeDocumentAttribute、NSCharacterEncodingDocumentAttribute 和 NSDefaultAttributesDocumentAttribute 是受支持的选项键。如果未指定,该方法会检查数据以尝试确定适当的属性。

NSParagraphStyleAttributeName 不是受支持的选项键,它被忽略。

但是,您可以尝试将&lt;center&gt; 附加到 HTML,如下所示:

"<center><span style=\"color: rgb(158, 29, 255);\"><b>This</b> is a <i>simple</i> <u>text</u>.</span></center>"

【讨论】:

    【解决方案2】:

    试试这个

    1) 获取 UIWebView 和 UITextView。

    2) 在 WebView 中设置您的属性字符串。

    [webView loadHTMLString:[yourAttributedString stringByReplacingOccurrencesOfString:@"\n" withString:@"<br/>"] baseURL:nil];
    

    3) 从 UIWebView 获取您的 HTML 字符串。

    NSString *simpleHtmlString = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      相关资源
      最近更新 更多