简体   繁体   中英

Attributed string not showing bold and italic text with a specific font

I am receiving an html string which I need to display using UILabel. In case, I don't add UIFont then I see the string as expected.

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

在此处输入图片说明

But the font is extremely small, so I need to modify it.

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

Now, I see text as

在此处输入图片说明

Any other way of setting font while maintaining the attributes?

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

This may help you...!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM