Search code examples
cocoanstokenfield

NSTokenField set maximal number of Token


Let's say, I have a TokenField, where the user can input who the message should be sent to. But I don't want that the user can input more than 3 Token.

Is there a way to achieve this?


Solution

  • Implement NSTokenField Delegate tokenField:shouldAddObjects:atIndex:

    // return an array of represented objects you want to add.
    // If you want to reject the add, return an empty array.
    
    - (NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)tokens atIndex:(NSUInteger)index
    {
        if (index>2) {
            return [NSArray array];
        }
        NSLog(@"%@-- %d %d", tokens, [tokens count],index);
        return tokens;
    }