【问题标题】:NSTextFieldCell with Multiple Lines具有多行的 NSTextFieldCell
【发布时间】:2011-07-01 19:59:34
【问题描述】:

我需要显示一个 NSTextFieldCell,其中包含多行,每行具有不同的格式。

类似这样的:

第 1 行:标题
第 2 行:描述

我继承了 NSTextFieldCell,但我不知道如何继续。

有什么想法吗?

【问题讨论】:

    标签: objective-c cocoa nsoutlineview nscell nstextfieldcell


    【解决方案1】:

    首先,您没有有子类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...

    【讨论】:

    • 谢谢,我试试看。 :D
    【解决方案2】:

    使用NSTextView 有什么问题?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      相关资源
      最近更新 更多