我正在将一个简单的 HTML 加载到 NSTextView 中。我已经为 NSTextView 设置了字体属性,但是 HTML 的加载会忽略这些字体,并且默认始终为“Times-Roman 12 大小”。目前我正在枚举属性并设置字体大小。但是仅仅为了改变大小而这样做似乎很昂贵。这是唯一的方法吗?有没有更好的办法?
HTML:
<p>This is just a <b>title</b></p>
将 HTML 加载到 NSTextView 并随后更改字体大小:
NSData *valueInDataFormat = [bodyContent dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *textToBeInserted = [[NSAttributedString alloc] initWithHTML:valueInDataFormat documentAttributes:nil];
NSDictionary *rtfTextAttributes = [self defaultTextAttributesFor:RTFText];
//inserttext mimic what user do; so it takes the typingattributes
//ref: http://www.cocoabuilder.com/archive/cocoa/113938-setting-default-font-of-an-nstextview.html#114071
[entryContent setString:@""];
[entryContent setTypingAttributes:rtfTextAttributes];
[entryContent insertText:textToBeInserted];
//now change font size
NSTextStorage *content = [entryContent textStorage];
[content beginEditing];
NSRange totalRange = NSMakeRange (0, content.length);
[content enumerateAttributesInRange: totalRange
options: 0
usingBlock: ^(NSDictionary *attributes, NSRange range, BOOL *stop) {
NSLog (@"range: %@ attributes: %@",
NSStringFromRange(range), attributes);
NSFont *font = [attributes objectForKey:NSFontAttributeName];
if (font){
[content removeAttribute:NSFontAttributeName range:range];
font = [[NSFontManager sharedFontManager] convertFont:font toSize:[font pointSize] + 3];
[content addAttribute:NSFontAttributeName value:font range:range];
}
}];
[content endEditing];
[entryContent didChangeText];