iOS 7 using an HTML string as an NSAttributedStrin

2019-07-16 18:59发布

I have a UITextView in which I'm trying to display some attributed text which comes in the form of HTML. It uses things like inline bolding and italicizing. The client now wants the font on this to change. However, whenever I change the font, it seems to disregard any of the HTML formatting. Is there any way to change the font while retaining the other formatting attributes, like bolding an italicizing?

2条回答
你好瞎i
2楼-- · 2019-07-16 19:37

For an objective-c approach, I used NSMutableString and -setAttributes:

NSString *htmlString = @"..."
NSData *textData = [htmlString dataUsingEncoding:NSUnicodeStringEncoding];
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]
      initWithData:textData
           options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType }
documentAttributes:nil error:nil];
[attrStr setAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"avenir" size:12.0f]} range:NSMakeRange(0,attrStr.length)];
查看更多
Juvenile、少年°
3楼-- · 2019-07-16 19:38

The way I was able to get it to work was to prepend my string with <span style=\"font-family: Avenir; font-size: 12\">%@</span>

查看更多
登录 后发表回答