How to check all tokens are valid in NSTokenField

Apple has developed a callback method that can verify that the new tokens added to the NSTokenField are valid:

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

I implemented this, and it turns out that it works fine, except for one case. If the user begins to enter a token, but has not yet completed entering the token, and the user presses the TAB key, the verification method is not called.

This means that I can guarantee that all entered tokens are valid, if the user does not work, they can click the tab to bypass the check.

Does anyone know what is the right way to deal with this situation?

+8
objective-c cocoa nstokenfield
source share
2 answers

I tried for a while and I found that the token field calls control: isValidObject: from the NSControlTextEditingDelegate protocol when you press the Tab key. This way you can implement the delegate method like

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

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

+7
source share

I am also struggling with this problem and found that using the: isValidObject control, as suggested by zonble, almost comes to a solution, but 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 limited only to the tab key, so I implemented a couple of methods as follows:

I understand that this is terribly ugly, but this is the only way to get an NSTokenField to avoid creating tokens in a tab without affecting other NSTextField behaviors for an NSTokenField (e.g. 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; } 
+2
source share

All Articles