处理NSTokenField中的重复选择

问题描述:

如何防止重复选择NSTokenField中的数组。我已经实现了delegate completionsForSubstring。处理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) { 
     ; 
    } 
} 
+0

要完全拒绝添加,返回一个空数组。返回nil会导致错误。 –

+0

由于'[tokenField objectValue]'已经是'shouldAdd'中的新值,所以这不起作用。 – Cathy

我能够去除这种方法,这诚然是一个小哈克任何重复,但它的工作原理:

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