Search code examples
objective-ccocoamacosappkitnstokenfield

Resizing NSTokenField after populating with tokens


I am using an NSTokenField as a way for users to enter tags. Everything works fine and it hooks up with CoreData managing the tags both when the user adds or deletes a tag.

I recently added logic so that the NSTokenField would resize vertically as the user adds tags and they break to the next line using Andrew Bowman's IFVerticallyExpandingTextField. Again this all works fine.

The issue is that when I have to initially populate the NSTokenField with tags, I need it to resize. I populate the field by calling:

[tagField setObjectValue: anArray];

Where anArray is a series of objects that represent a tag or a Token. This in turn calls the NSTokenField delegate method

tokenField:displayStringForRepresentedObject:

Which returns the string representation for the object passed in the previous array.

I need to resize the NSTokenField after all of the calls to displayStringForRepresentedObject. Does anyone have any ideas of a notification or a way of finding out that it's all done? Even a way of calling the resize in between each call to displayStringForRepresentedObject would probably work.

Thanks in advance.


Solution

  • You might try something similar to -setNeedsDisplay: and -displayIfNeeded ... i.e., -setNeedsSizeToFit: and -sizeToFitIfNeeded.

    You'll just need a "needsSizeToFit" BOOL flag and the -setNeedsSizeToFit: and -sizeToFitIfNeeded methods.

    After you set your tokens, call -setNeedsSizeToFit:YES. It in turn will set the instance's needsSizeToFit flag, then if the flag is YES, it will call [self performSelector:@selector(sizeToFitIfNeeded) withObject:nil afterDelay:0]. Your -sizeToFitIfNeeded method will check if your needsSizeToFit flag is YES, call [self sizeToFit], then set the needsSizeToFit flag to NO.

    Update

    Here's a complete class (JLNAutoSizingTokenField) that does basic autosizing as described above. The only augmentation was to call this in the afore-mentioned delegate method:

    - (NSString *)tokenField:(NSTokenField *)aTokenField 
    displayStringForRepresentedObject:(id)representedObject
    {
        [(JLNAutoSizingTokenField *)aTokenField setNeedsSizeToFit:YES];
        return representedObject;
    }