Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTokenField does not check token on blur

I have an NSTokenField which allows the user to select contacts (Just like in Mail.app). So the NSTextField is bound to an array in my model.recipient instance variable.

The user can now select an entry from the auto completion list e.g. Joe Bloggs: [email protected] and as soon as he hits Enter the token (Joe Bloggs) is displayed and model.recipients now contains a BBContact entry.

Now if the user starts to type some keys (so the suggestions are shown) and then hits Tab instead of Enter the token with the value of the completion text (Joe Bloggs: [email protected]) is created and the NSTokenFieldDelegate methods did not get called, so that I could respond to this event. The model.recipient entry now contains an NSString instead of a BBContact entry.

Curiously the delegate method tokenField:shouldAddObjects:atIndex: does not get called, which is what I would expect when the user tabs out of the token field.

enter image description here

like image 978
Besi Avatar asked Aug 16 '11 12:08

Besi


1 Answers

Pressing tab calls isValidObject on the delegate so return NO for NSTokenField in it however you want to return YES if there are no alphanumeric characters in it otherwise the user won't be able to focus away from the field (the string contains invisible unicode characters based on how many tokens exist)

The less fragile implementation i could come up with is:

- (BOOL)control:(NSControl *)control isValidObject:(id)token
{
    if ([control isKindOfClass:[NSTokenField class]] && [token isKindOfClass:[NSString class]])
    {
        if ([token rangeOfCharacterFromSet:[NSCharacterSet alphanumericCharacterSet]].location == NSNotFound) return YES;
        return NO;
    }
    return YES;
}
like image 122
valexa Avatar answered Nov 05 '22 19:11

valexa