I want to add a button to my application in the NSTokenField field, for example something like this:

enter image description here

Ie, in NSTokenField there is a plus button that should perform some action, for example a pop-up menu with a choice of tokens that can be added to the NSTokenField field.

I created the button programmatically and added it to the NSTokenField:

NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(185, -1, 19, 24)]; [button setTitle:@"<"]; [button setFont:[NSFont menuFontOfSize:[NSFont smallSystemFontSize]]]; [button setButtonType:NSMomentaryPushInButton]; [button setBezelStyle:NSSmallSquareBezelStyle]; [button setTarget:self]; [button setAction:@selector(action:)]; [formatTokenField addSubview:button]; 

The button was added normally:

enter image description here

but when I try to enter characters in the NSTokenField the input area overlaps my button:

enter image description here

Please help me figure out how to add buttons to the NSTokenField correctly and what needs to be done so that the input area does not overlap the added buttons (could you give some code examples). Thank you all in advance.

    1 answer 1

    Maybe I do not understand the idea and the proposal is wrong. But why not just place this button next?

     NSRect tfFrame = formatTokenField.frame; CGFloat btnWidth = 19.0f; NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(tfFrame.origin.x + tfFrame.size.width - 1, tfFrame.origin.y - 1, btnWidth, tfFrame.size.height + 2)]; ... [[self view] addSubview:button]; //view на котором formatTokenField 

    Well, or if you want this way, then you need to inherit from NSTokenFieldCell and override the drawingRectForBounds function:

     #import <Cocoa/Cocoa.h> @interface ExtCell : NSTokenFieldCell @end @implementation ExtCell - (NSRect) drawingRectForBounds:(NSRect)rect { CGFloat vIndent = 2; //отступ сверху CGFloat hIndent = 2; // отступ сбоку CGFloat tfWidth = 185; //ширина поля ввода (ширина TokenField за вычетом отступов, ширины кнопки и прочего по усмотрению) CGFloat tfHeight = 20; //высота поля ввода (высота TokenField за вычетом отступов и прочего по усмотрению) NSRect newRect = CGRectMake(hIndent, vIndent, tfWidth, tfHeight); return newRect; } @end 

    enter image description here

    Values ​​of vIndent and others change for normal for the case.

    Result:

    enter image description here enter image description here