2011-07-01 29 views
6

Tôi cần hiển thị NSTextFieldCell với nhiều dòng với định dạng khác nhau trên mỗi dòng.NSTextFieldCell với nhiều dòng

Something như thế này:

Dòng 1: Tiêu đề
Dòng 2: Mô tả

Tôi subclassed NSTextFieldCell nhưng tôi không biết làm thế nào để đi về với nó.

Bất kỳ ý tưởng nào?

Trả lời

8

Trước hết, bạn không phân lớp NSTextFieldCell để đạt được điều này, vì, như một lớp con của NSCell, NSTextFieldCell thừa hưởng -setAttributedStringValue:. Chuỗi bạn cung cấp có thể được biểu diễn dưới dạng NSAttributedString. Mã sau đây minh họa cách bạn có thể đạt được văn bản mong muốn với một số thông thường 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 

Điều này dẫn đến những điều sau đây:

enter image description here

Bây giờ, tùy thuộc vào cách bạn định cho điều này văn bản được sử dụng, bạn có thể triển khai thiết kế theo nhiều cách khác nhau ent cách. Bạn có thể muốn xem liệu một số NSTextView có thể hoạt động cho bạn thay vì một số NSTextField ...

+0

Cảm ơn, tôi sẽ thử. : D – mikywan

Các vấn đề liên quan