2011-08-16 39 views
7

我有一個NSTokenField它允許用戶選擇聯繫人(就像在Mail.app中一樣)。所以NSTextField綁定到我的model.recipient實例變量中的一個數組。NSTokenField不檢查模糊令牌

用戶現在可以從自動完成列表中選擇一個條目,例如Joe Bloggs: [email protected]並且一旦他擊中輸入顯示令牌(Joe Bloggs)並且model.recipients現在包含BBContact條目。

現在,如果用戶開始輸入一些鍵(這樣的建議顯示),然後點擊標籤,而不是與創建(Joe Bloggs: [email protected])完成文本的價值和NSTokenFieldDelegate方法沒有得到所謂的輸入令牌,這樣我才能迴應這個事件。 model.recipient條目現在包含NSString而不是BBContact條目。

奇怪的是代理方法tokenField:shouldAddObjects:atIndex:沒有被調用,這是我期望當用戶退出令牌字段。

enter image description here

回答

6

按Tab鍵調用委託上的isValidObject,因此在其中返回NSTokenField的NO,但是如果沒有字母數字字符,則返回YES,否則用戶將無法遠離該字段(該字符串包含)的基礎上如何存在着許多無形的令牌Unicode字符

的那麼脆弱實現我能想出是:

- (BOOL)control:(NSControl *)control isValidObject:(id)token 
{ 
    if ([control isKindOfClass:[NSTokenField class]] && [token isKindOfClass:[NSString class]]) 
    { 
     if ([token rangeOfCharacterFromSet:[NSCharacterSet alphanumericCharacterSet]].location == NSNotFound) return YES; 
     return NO; 
    } 
    return YES; 
} 
-1

這可能是因爲「ENTER」鍵可以發送令牌領域到它的行動,其中「Tab」鍵只是將文本添加到它的事件。您可以嘗試將-isContinuous屬性設置爲YES並查看您是否獲得了期望的結果。

+0

這聽起來前途,所以我趕緊嘗試過了,但問題仍然存在,所以我仍然有同樣的行爲。 – Besi

+0

我現在正在使用'isValidObject'回調工作 – Besi

0

我能解決使用@ valexa的建議問題。如果模糊TAB我必須通過所有條目,並查找我的聯繫對象的任何字符串。

- (BOOL)control:(NSControl *)control isValidObject:(id)token{ 
    if ([control isKindOfClass:[NSTokenField class]] && [token isKindOfClass:[NSString class]]) 
    { 
     NSTokenField *tf = (NSTokenField *)control; 

     if ([token rangeOfCharacterFromSet:[NSCharacterSet alphanumericCharacterSet]].location == NSNotFound){ 
      return YES; 
     } else { 

      // We get here if the user Tabs away with an entry "pre-selected" 
      NSMutableArray *set = @[].mutableCopy; 
      for(NSObject *entry in tf.objectValue){ 

       GSContact *c; 
       if([entry isKindOfClass:GSContact.class]){ 
        c = (GSContact *)entry; 
       } 

       if([entry isKindOfClass:NSString.class]){ 

        NSString *number = [[(NSString *)entry stringByReplacingOccurrencesOfString:@">" withString:@""] 
             componentsSeparatedByString:@"<"][1]; 
        c = [self findContactByNumber:number]; 
       } 

       if(c) [set addObject:c]; 
      } 

      [control setObjectValue:set]; 
     } 
    } 
    return YES; 
} 

enter image description here

+0

你授予我的解決方案的具體實現回答這個問題的要點嗎?我認爲這可能違背了計算器的規則。 – valexa