Search code examples
objective-ccocoanstokenfield

How to validate all tokens are valid in an NSTokenField


Apple have conveniently created a callback method that allows you to check that the new tokens that are being added to an NSTokenField are valid:

- (NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)newTokens atIndex:(NSUInteger)index

I have implemented this, and it turns out that it works great except for in one case. If the user starts typing in a token, but has not yet completed typing the token, and the user presses the TAB key, the validation method is not called.

This means I am able to ensure that all tokens that are entered are valid unless the user works out they can press tab to bypass the validation.

Does anyone know what the correct way to handle this situation is?


Solution

  • I tried for a little while and I found that the token field calls control:isValidObject: of the NSControlTextEditingDelegate protocol when the Tab key is pressed. So you can implement a delegate method such as

    - (BOOL)control:(NSControl *)control isValidObject:(id)object
    {
        NSLog(@"control:%@", control);
        NSLog(@"object:%@", object);
        return NO;
    }
    

    The 'object' parameter is the content of your incomplete token. If the method returns NO, the token will not be inserted to the array of valid tokens.