How to validate all tokens are valid in an NSTokenField

Viewed 1071

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?

3 Answers

I've tried a slightly different approach and instead watch for the tab key, changing it to a return key. This delegate method first confirms it's the relevant token field and checks the command selector.)

Apologies for leaving this answer in Swift - hopefully allowable given the intervening 8.5 years.

func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool
{
    if control == tokenField, // my interested token field
        commandSelector == #selector(insertTab(_:))
    {
        textView.insertNewline(self)
        return true
    }
    
    return false
}
Related