我需要在每一行上显示一个具有不同格式的多行NSTextFieldCell。
就像这样:
第1行:标题
第2行:说明
我对NSTextFieldCell进行了子类化,但我不知道如何继续下去。
有什么想法吗?
发布于 2011-07-02 02:25:24
首先,不需要子类NSTextFieldCell来实现这一点,因为作为NSCell的子类,NSTextFieldCell继承了-setAttributedStringValue:。您提供的字符串可以表示为NSAttributedString。下面的代码说明了如何使用普通的NSTextField实现所需的文本。
MDAppController.h:
@interface MDAppController : NSObject <NSApplicationDelegate> {
IBOutlet NSWindow *window;
IBOutlet NSTextField *textField;
}
@endMDAppController.m:
@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这样做的结果如下:

现在,取决于您打算如何使用此文本,您可以通过几种不同的方式实现该设计。您可能想看看NSTextView是否适合您,而不是NSTextField.
发布于 2011-07-02 13:44:25
使用NSTextView有什么问题
https://stackoverflow.com/questions/6552682
复制相似问题