我需要显示一个包含多行且每行格式不同的 NSTextFieldCell 。
像这样的事情:
Line 1: Title
2号线:描述
我对 NSTextFieldCell 进行了子类化,但我不知道如何继续使用它。
有任何想法吗?
首先,你不have子类化NSTextFieldCell
为了实现这一点,因为,作为NSCell
, NSTextFieldCell
继承-setAttributedStringValue:
。您提供的字符串可以表示为NSAttributedString
。下面的代码说明了如何使用普通的文本来实现所需的文本NSTextField
.
MDAppController.h:
@interface MDAppController : NSObject <NSApplicationDelegate> {
IBOutlet NSWindow *window;
IBOutlet NSTextField *textField;
}
@end
MDAppController.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
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)