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];
但是,它没有将属性字符串设置为居中对齐。怎么了?
答案 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"];