开发者

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开发者_C百科 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?


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.


I'm also struggling with this problem and found that using control:isValidObject as suggested by zonble almost gets to the solution, but that it is difficult to determine whether to return NO or YES based on the object parameter. As far as I can tell this problem is only restricted to the tab key so I implemented a pair of methods as follows;

I realise that this is horribly ugly but it's the only way I could get the NSTokenField to avoid creating tokens on tab while not impinging on other NSTextField behaviours of NSTokenField (eg moving the cursor to a new position etc).

- (BOOL)control:(NSControl *)control isValidObject:(id)object
{
    if (self.performingTab) {
        self.performingTab=NO;
        return NO;
    } else {
        return YES;
    }
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)fieldEditor
doCommandBySelector:(SEL)commandSelector 
{        
    if (commandSelector==@selector(insertTab:)) {
        self.performingTab=YES;
    }        
    return NO;        
}


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜