从HTML字符串转换时,如何使NSAttributedString居中对齐?

时间:2015-11-21 04:59:16

标签: ios nsattributedstring

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];

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

2 个答案:

答案 0 :(得分:0)

根据NSAttributedString的文件:

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

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

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

但是,您可以尝试将<center>添加到HTML中,如下所示:

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

答案 1 :(得分:0)

Try this

1) Take UIWebView and UITextView.

2) Set your Attributed string in WebView.

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

3) Get your HTML string from UIWebView.

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