【问题标题】:How to prevent NSSearchField from overwriting entered strings using the first autocompletion list entry?如何防止 NSSearchField 使用第一个自动完成列表条目覆盖输入的字符串?
【发布时间】:2010-10-20 19:12:02
【问题描述】:

我正在寻找一种方法来创建一个行为如下的 nssearchfield:

  • 用户输入文本
  • 根据匹配出现自动完成下拉菜单
  • 搜索字段中的文本不会自动补全到列表中的第一项

关键是,我的字符串匹配搜索任何子字符串和文本字段中的自动完成将不起作用,因为它会覆盖我输入的字符串。事实上,这似乎应该是默认行为,还是我误解了搜索字段的目的?
进一步键入会进一步限制列表,但只有在自动完成下拉列表中选择了一个项目后,该项目才会插入到文本字段中。

如果这不能使用 nssearchfield 完成,是否有替代方法?

【问题讨论】:

    标签: cocoa macos autocomplete nssearchfield


    【解决方案1】:

    我自己的解决方案实际上非常简单:只需将搜索字符串本身添加到自动完成的建议列表中即可。
    这是在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;
    

    【讨论】:

    • 这很聪明,我喜欢。如果建议有多个单词,这会导致问题。它适用于第一个单词,但之后它会在第一个单词之后插入完整的建议。我想知道有没有办法解决这个问题。
    • 回答了我自己的问题。请参阅我对stackoverflow.com/questions/5163646/… 的回答,了解如何避免在输入空格后自动完成。
    • @jeremy 你能解释一下你的答案吗,我想在输入空格后实现同样的自动完成?
    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2020-02-23
    • 2014-04-16
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多