Objective c 多行NSTextFieldCell
我需要显示一个NSTextFieldCell,它有多行,每行的格式不同 大概是这样的: 第1行:标题Objective c 多行NSTextFieldCell,objective-c,cocoa,nsoutlineview,nscell,nstextfieldcell,Objective C,Cocoa,Nsoutlineview,Nscell,Nstextfieldcell,我需要显示一个NSTextFieldCell,它有多行,每行的格式不同 大概是这样的: 第1行:标题 第2行:说明 我将NSTextFieldCell子类化,但我不知道如何继续 有什么想法吗?首先,您不必为NSTextFieldCell创建子类,因为作为NSCell的子类,NSTextFieldCell继承了-setAttributedStringValue:。您提供的字符串可以表示为NSAttributedString。以下代码说明了如何使用普通的NSTextField实现所需的文本 MDAp
第2行:说明 我将NSTextFieldCell子类化,但我不知道如何继续 有什么想法吗?首先,您不必为
NSTextFieldCell
创建子类,因为作为NSCell
的子类,NSTextFieldCell
继承了-setAttributedStringValue:
。您提供的字符串可以表示为NSAttributedString
。以下代码说明了如何使用普通的NSTextField
实现所需的文本
MDAppController.h:
@interface MDAppController : NSObject <NSApplicationDelegate> {
IBOutlet NSWindow *window;
IBOutlet NSTextField *textField;
}
@end
其结果如下:
现在,根据您打算如何使用本文,您可以用几种不同的方式实现设计。您可能想看看
NSTextView
是否适合您,而不是NSTextField
。使用有什么问题?谢谢,我会尝试一下D
@implementation MDAppController
static NSDictionary *regularAttributes = nil;
static NSDictionary *boldAttributes = nil;
static NSDictionary *italicAttributes = nil;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
if (regularAttributes == nil) {
regularAttributes = [[NSDictionary dictionaryWithObjectsAndKeys:
[NSFont systemFontOfSize:[NSFont systemFontSize]],NSFontAttributeName,
nil] retain];
boldAttributes = [[NSDictionary dictionaryWithObjectsAndKeys:
[NSFont boldSystemFontOfSize:[NSFont systemFontSize]],NSFontAttributeName,
nil] retain];
NSFont *regFont = [NSFont userFontOfSize:[NSFont systemFontSize]];
NSFontManager *fontManager = [NSFontManager sharedFontManager];
NSFont *oblique = [fontManager convertFont:regFont
toHaveTrait:NSItalicFontMask];
italicAttributes = [[NSDictionary dictionaryWithObjectsAndKeys:
oblique,NSFontAttributeName, nil] retain];
}
NSString *string = @"Line 1: Title\nLine 2: Description";
NSMutableAttributedString *rString =
[[[NSMutableAttributedString alloc] initWithString:string] autorelease];
[rString addAttributes:regularAttributes
range:[string rangeOfString:@"Line 1: "]];
[rString addAttributes:regularAttributes
range:[string rangeOfString:@"Line 2: "]];
[rString addAttributes:boldAttributes
range:[string rangeOfString:@"Title"]];
[rString addAttributes:italicAttributes
range:[string rangeOfString:@"Description"]];
[textField setAttributedStringValue:rString];
}
@end