2017-07-20 1 views
1

J'ai une chaîne NSAttributed de ma vue UIText, et je veux le traduire en NSString et l'enregistrer. donc j'utiliser ces codes pour fait:iOS: Comment enregistrer NSAttributedString en chaîne

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

}

Lorsque la prochaine fois, je veux afficher dans mon textView, j'utilise ces codes pour traduire en NSAttributedString:

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

Et j'ai trouvé que ses modifications attribuées. Par exemple: Je l'enregistre. enter image description here

Et puis je charge et traduit à NSAttributedstring. enter image description here

Comment puis-je résoudre ce problème.

+0

@Codus Oh , Je veux dire que j'ai quelques attrib utedstring forme mon textview, et l'enregistre en tant que chaîne html + css tout comme pic1.la prochaine fois que je charge cette chaîne et la traduit en attributestring et trouve une valeur d'attribut modifiée.Un problème dans mon code pour traduire NSString en NSAttributedstring? – Darsky

Répondre

0

C'est parce que HTML4 VS HTML5.

  1. Vous HTML4 obtenu lorsque vous traduisez NSAttributedString en html. Mais le contenu de html juste traduit devrait être HTML5. Lorsque vous remettez le code HTML, il semble plus grand.

Alors, quand vous continuez à traduire NSAttributedString et mettre html en arrière, il gardera générer HTML4 et remettre en HTML5 (faire la taille de police plus grande).

comme ceci:

NSAttributedString -> HTML4 -> NSAttributedString

Keep export NSAttributedString to html and put it back

Vous pouvez essayer d'effacer marque HTML4 pour laisser NSAttributedString analyser correctement traduit html à HTML5.

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

comme ceci:

NSAttributedString -> HTML4 -> comme HTML5 -> NSAttributedString

Keep export NSAttributedString to html and put it back as HTML5

+0

Merci, et j'ai essayé de changer , mais cela n'a pas fonctionné .... – Darsky

+0

Merci beaucoup et j'ai trouvé que c'est un problème avec pt et px. – Darsky

-1
NSString *str = [attri string];