How to implement a multiline NSTokenField?

486 views Asked by At

I want to implement an NSTokenField that spans multiple lines. For example:

Multi-line NSTokenField

I found a some sample code of multi-line NSTokenField on the internet:

IBOutlet NSTokenField *tokenField;

- (void)awakeFromNib
{
    [[tokenField cell] setWraps:YES];
}

made my class delegate of the NSTokenField and implement the following method

- (void)controlTextDidChange:(NSNotification *)obj {    
    NSRect oldTokenFieldFrame = [tokenField frame];
    NSRect tokenFieldBounds = [tokenField bounds];

    float height = oldTokenFieldFrame.size.height;
    tokenFieldBounds.size.height = CGFLOAT_MAX;
    NSSize cellSize = [[tokenField cell] cellSizeForBounds:tokenFieldBounds];

    float y = oldTokenFieldFrame.origin.y + height - cellSize.height;

    [tokenField setFrame:NSMakeRect(oldTokenFieldFrame.origin.x,
                                          y,
                                          oldTokenFieldFrame.size.width,
                                          cellSize.height)];
}

but this code does not work correctly.

Could you please help me with this issue?

Thank you in advance.

1

There are 1 answers

0
Jan Z. On

For everybody who is just looking for an answer with working code, I've found this super short solution. Here we go:

#import "MyExpandingTokenField.h"

@implementation MyExpandingTokenField

- (NSSize)intrinsicContentSize {
    NSSize intrinsicContentSize = [self sizeThatFits:NSMakeSize(self.frame.size.width, CGFLOAT_MAX)];
    intrinsicContentSize = NSMakeSize(intrinsicContentSize.width, intrinsicContentSize.height + 5);
    return intrinsicContentSize;
}

- (void)textDidChange:(NSNotification *)notification {
    [super textDidChange:notification];
    [self invalidateIntrinsicContentSize];
}

@end