How to validate all tokens are valid in an NSTokenField

孤街浪徒 提交于 2019-12-10 12:47:38

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/6359121/how-to-validate-all-tokens-are-valid-in-an-nstokenfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!