2017-08-18 55 views
0

我收到一个需要使用UILabel显示的html字符串。如果我不添加UIFont,那么我会按预期看到字符串。Attributed字符串不显示带有特定字体的粗体和斜体文本

+(NSAttributedString *)getAttributedText:(NSString *)text { 
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 
return attrStr; 
} 

enter image description here

但字体非常小,所以我需要修改它。

+(NSAttributedString *)getAttributedText:(NSString *)text { 
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 
NSMutableAttributedString *newString = [[NSMutableAttributedString alloc] initWithAttributedString:attrStr]; 
NSRange range = (NSRange){0,[newString length]}; 
[newString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"OpenSans" size:14.0] range:range]; 
return newString; 
} 

现在,我看到的文本作为

enter image description here

设置字体,同时保持属性的任何其他方式?

+0

因为斜体和粗体是INSIF'UIFont',所以当你替换它时,它会改变这一切。你可以修改自己的HTMLString,或遍历'NSAttributedString'。 – Larme

+0

请检查我的答案 –

回答

0
+(NSAttributedString *)getAttributedText:(NSString *)text { 
     text = [text stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-size:%fpx;}</style>", 15]]; // Font size that you want to display for text 

     NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] 
                   options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
                     NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                documentAttributes:nil 
                   error:nil]; 
} 

这可能会帮助你...... !!!

+0

嘿 - 这可以用于字体大小和名称? –

+0

text = [text stringByAppendingString:[NSString stringWithFormat:@“”, “字体名称”, “字体大小”]];;但你将如何识别哪个词将是粗体或下划线。所以最好使用大字号的相同字体。 –

相关问题