2014-11-06 71 views
0

我使用attributedText屬性label來呈現html。NSAttributedString不呈現html換行符

它與渲染粗體和斜體正常工作。但是,當我嘗試呈現HTML換行符時,它只會切斷換行符後出現的所有文本。

NSString* view = @"<i>Testing</i> and this is <b>bold</b> <br> This should be in next line"; 
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}; 

NSAttributedString *preview = [[NSAttributedString alloc] initWithData:[view dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil]; 
self.labelView.attributedText = preview; 

幫助需要

+0

也許你錯過了NSUTF8StringEncoding字符編碼部分解決,如下所示:http://stackoverflow.com/questions/4217820/convert-html-to-nsattributedstring-in -ios'[[NSAttributedString的alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 選項:@ {NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)} documentAttributes:無誤差:無];' – Zhang 2014-11-06 06:57:37

+0

我應該然後使用什麼編碼因爲html不會是網頁,但主要用於格式化文本 – 2014-11-06 06:59:02

+0

是否替換'@ {NSDocumentTypeDocumentAttribute:NSHTMLTextDoc umentType};'帶'@ {NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)};'help? – Zhang 2014-11-06 07:00:46

回答

0

我想和這個工作

NSString* view = @"<i>Testing</i> and this is <b>bold</b> <br> This should be in next line"; 
NSAttributedString *preview =[[NSAttributedString alloc] initWithData:[view dataUsingEncoding:NSUTF8StringEncoding] 
           options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
              NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
         documentAttributes:nil error:nil]; 

UILabel *lbl = [[UILabel alloc] initWithFrame:cell.textLabel.frame]; 
[lbl setAttributedText:preview]; 
0

正如在評論中提到的,對我來說這個問題是不是與HTML渲染但忘記設置「線路數量「在UILabel上爲0。

0

我有一些關於此問題的問題,並獲取ASCII代碼,而不是像'&'和一些其他代碼一些特殊字符。所有的問題,只要使用:

NSString *html = [command.arguments objectAtIndex: 
NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding]; 
NSDictionary *dict = @{@"WebMainResource": @{@"WebResourceData": data, @"WebResourceFrameName": @"", @"WebResourceMIMEType": @"text/html", @"WebResourceTextEncodingName": @"UTF-8", @"WebResourceURL": @"about:blank"}}; 
data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:nil]; 
NSAttributedString *decodedString = [[NSAttributedString alloc] initWithData:data 
                     options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} 
                    documentAttributes:NULL 
                       error:NULL];`