NSTextFieldCell with multiple lines

I need to show an NSTextFieldCell with multiple lines with a different format on each line.

Something like that:

Line 1: Title
Line 2: Description

I have subclassed NSTextFieldCell, but I do not know how to proceed with it.

Any ideas?

+6
source share
2 answers

Firstly, this does not require a subclass of NSTextFieldCell , since, as a subclass of NSCell , NSTextFieldCell -setAttributedStringValue: inherited. The string you provided can be represented as NSAttributedString . The following code illustrates how you could achieve your desired text using a regular 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 

The result is the following:

enter image description here

Now, depending on how you intend to use this text, you can implement the design in several ways. You can see if NSTextView work for you, not NSTextField ...

+8
source

What is wrong with using NSTextView ?

+1
source

Source: https://habr.com/ru/post/891844/