归因字符串不显示带有特定字体的粗体和斜体文本

时间:2017-08-18 09:45:15

标签: ios objective-c nsattributedstring uifont

我收到一个html字符串,我需要使用UILabel显示。如果我没有添加UIFont,那么我会看到预期的字符串。

+(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

在保持属性的同时设置字体的其他方法吗?

1 个答案:

答案 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];
}

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