我正在將一個簡單的HTML加載到NSTextView中。我已經爲NSTextView設置了字體屬性,但是HTML的加載忽略了這些字體,默認值始終爲'Times-Roman 12 size'。目前我正在枚舉屬性並設置字體大小。但爲了改變尺寸,這樣做似乎很昂貴。這是唯一的方法嗎?有沒有更好的辦法?在將HTML加載到NSTextView時設置默認字體和大小
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];