2010-10-20 64 views
5

我正在尋找一種方式來創建行爲如下的nssearchfield:基於文本 如何防止NSSearchField使用第一個自動完成列表條目覆蓋輸入的字符串?

    • 用戶類型相匹配的自動完成下拉出現
    • 在搜索字段中的文本不自動完成的第一個項目在列表中

    的一點是,我的字符串匹配的文本字段中的任何字符串並自動完成搜索是行不通的,因爲它會奧雅納改寫我輸入的字符串。實際上,這似乎應該是默認行爲,還是我誤解了搜索字段的用途?
    進一步鍵入會進一步限制列表,但只有在自動完成下拉列表中選擇一個項目後,該項目纔會插入到文本字段中。

    如果這不能使用nssearchfield來實現,是否有其他選擇?

  • 回答

    3

    我自己的解決方案其實很簡單:只需將搜索字符串本身添加到自動完成建議列表中即可。
    這在NSSearchField委託方法control:textView:completions:forPartialWordRange:indexOfSelectedItem:完成:

    ... 
    partialString = [[textView string] substringWithRange:charRange]; 
    ... 
    
    matches  = [NSMutableArray array]; 
    
    // find any match in our keyword array against what was typed - 
    for (i=0; i< count; i++) 
    { 
    string = [keywords objectAtIndex:i]; 
    if ([string 
        rangeOfString:partialString 
        options: NSCaseInsensitiveSearch | NSForcedOrderingSearch 
        range:NSMakeRange (0, [string length])] 
        .location != NSNotFound) { 
        [matches addObject:string]; 
    } 
    } 
    [matches sortUsingSelector:@selector(compare:)]; 
    
    // Make sure we insert the already entered string, even if it does not 
    // match with any of the retrieved keywords. This will enter this string 
    // in the search field, as we intended, and it will not be overwritten 
    // with any match. 
    [matches insertObject:partialString atIndex: 0]; 
    
    return matches; 
    
    +0

    這是相當聰明的,我喜歡它。如果建議有多個詞,這會導致問題。它適用於第一個單詞,但之後會在第一個單詞後插入完整的建議。我想知道有沒有辦法解決這個問題。 – Jeremy 2011-03-02 05:32:50

    +0

    回答了我自己的問題。請參閱http://stackoverflow.com/questions/5163646/how-to-make-nssearchfield-send-action-upon-autocompletion/5360535#5360535關於如何在輸入空格後避免自動填充的答案。 – Jeremy 2011-03-19 06:20:53

    +0

    @jeremy你會解釋我更多關於你的答案,我想在輸入空格後實現相同的自動完成? – 2016-01-05 17:45:45

    相關問題