处理NSTokenField中的重复选择
答
我想说的最好的方法是实现代理shouldAddObjects
。将下面的代码写入委托中。
NSString *newVal = [[tokens objectAtIndex:0] description];
NSArray *aray = [tokenField objectValue];
for (NSString * token in aray) {
@try{
if ([token isEqual:newVal]){
return nil;
}
}
@catch (NSException *exception) {
;
}
}
答
我能够去除这种方法,这诚然是一个小哈克任何重复,但它的工作原理:
// Be sure to set the delegate of your NSTokenfield either in IB or in code.
#pragma mark - NSTokenFieldDelegate
-(NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)tokens atIndex:(NSUInteger)index{
double delayInSeconds = .1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSArray *aray = [tokenField objectValue];
NSOrderedSet *set = [NSOrderedSet orderedSetWithArray:aray];
aray = [set array];
[tokenField setObjectValue:aray];
});
return tokens;
}
要完全拒绝添加,返回一个空数组。返回nil会导致错误。 –
由于'[tokenField objectValue]'已经是'shouldAdd'中的新值,所以这不起作用。 – Cathy