2017-07-20 18 views
1

我從我的UIText視圖中有一個NSAttributedstring, ,我想將它翻譯爲NSString並保存。 所以我使用這些代碼,使其:iOS:如何將NSAttributedString保存爲字符串

- (NSString *)attriToStrWithAttri:(NSAttributedString *)attri{ 
NSDictionary *tempDic = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, 
          NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]}; 
NSData *htmlData = [attri dataFromRange:NSMakeRange(0, attri.length) 
        documentAttributes:tempDic 
            error:nil]; 

return [[NSString alloc] initWithData:htmlData 
          encoding:NSUTF8StringEncoding]; 

}

在接下來的時間,我想在我的TextView來顯示它,我使用這些代碼翻譯成NSAttributedString:

NSAttributedString *attrStr =[[NSAttributedString alloc] initWithData:[self.richTextString dataUsingEncoding:NSUTF8StringEncoding] 
                    options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, 
                      NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} 
                 documentAttributes:nil 
                    error:nil]; 

我發現它的屬性更改。例如: 我保存它。 enter image description here

然後我加載並轉換爲NSAttributedstring。 enter image description here

我該如何處理這個問題。

+0

@Codus哦,我的意思是我有一些屬性utedstring形成我的textview,並將其保存爲html + css字符串,就像pic1.下一次我加載此字符串並將其轉換爲歸檔字符串,並發現一些屬性值changed.Is在我的代碼中將NSString轉換爲NSAttributedstring有任何問題? – Darsky

回答

0

這是因爲HTML4 VS HTML5。

  1. 當你翻譯NSAttributedString到HTML中你會得到HTML4

  2. 但剛剛翻譯好的html的內容應該是HTML5。當你把html放回去時,它會看起來更大。

所以,當你把翻譯NSAttributedString,把HTML回來了,它會不斷產生HTML4並把它早在HTML5(使字體大小大)。

這樣的:

NSAttributedString - > HTML4 - > NSAttributedString

Keep export NSAttributedString to html and put it back

你可以試着抹去HTML4標記讓NSAttributedString正確解析HTML轉換到HTML5。

EX:變化<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><!DOCTYPE html>

這樣的:

NSAttributedString - > HTML4 - >如HTML5 - > NSAttributedString

Keep export NSAttributedString to html and put it back as HTML5

+0

謝謝,我已經嘗試更改爲<!DOCTYPE html>,但它沒有工作.... – Darsky

+0

非常感謝,我發現這是關於pt和px的問題。 – Darsky

-1
NSString *str = [attri string]; 
相關問題