3

我正在尝试使用来自我的自定义 NSSearchField 的搜索查询在 NSTextView 中实现搜索。

听起来很简单,但我无法让它工作。

到目前为止,我已经浏览了所有关于NSTextFinder、其客户端和 FindBarContainer 的 Apple 文档。TextFinder 只是将 FindBarView 提供给容器,当您激活搜索时,容器会显示它。

客户端、容器和 TextFinder 之间的所有通信都是隐藏的。它看起来就像一个黑匣子,旨在“按原样”工作,无需任何定制或干扰。

但是- (void)performAction:(NSTextFinderAction)opNSTextFinder 的方法呢?不是用于向 TextFinder 发送自定义命令吗?

我试图使用以下内容为其分配一个新的搜索字符串:

    NSPasteboard* pBoard = [NSPasteboard pasteboardWithName:NSFindPboard];
    [pBoard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeString, NSPasteboardTypeTextFinderOptions, nil] owner:nil];
    [pBoard setString:_theView.searchField.stringValue forType:NSStringPboardType];
    NSDictionary * options = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithBool:YES], NSTextFinderCaseInsensitiveKey,
                              [NSNumber numberWithInteger:NSTextFinderMatchingTypeContains], NSTextFinderMatchingTypeKey,
                              nil];

    [pBoard setPropertyList:options forType:NSPasteboardTypeTextFinderOptions];

    [textFinder performAction:NSTextFinderActionSetSearchString];

但这不起作用,只会破坏正常的 findBar 操作。

我有一种强烈的感觉,我做错了什么。我想要的只是在我自己的 NSSearchField 中有一个标准的搜索功能。那可能吗?

我敢打赌,我不是第一个对普通 findBar 不满意的人。

非常需要和感谢您的帮助!

4

1 回答 1

0

您可以使用NSComboBox. 使用以下委托返回搜索值:

- (NSString *)comboBox:(NSComboBox *)aComboBox completedString:(NSString *)substring
{    
    if ([aComboBox tag] == 101 || [aComboBox tag] == 102) {
        NSArray *currentList;
        if ([aComboBox tag] == 101) {
            NSArray *keyArray = keySuggestions;
            currentList = keyArray;
        } else {
            currentList = [NSArray arrayWithArray:self.valueSuggestions];
        }
        NSEnumerator *theEnum = [currentList objectEnumerator];
        id eachString;
        NSInteger maxLength = 0;
        NSString *bestMatch = @"";
        while (nil != (eachString = [theEnum nextObject])) {
            NSString *commonPrefix = [eachString
                                      commonPrefixWithString:substring options:NSCaseInsensitiveSearch];
            if ([commonPrefix length] >= [substring length] && [commonPrefix
                                                                length] > maxLength)
            {
                maxLength = [commonPrefix length];
                bestMatch = eachString;
                break;
            }
        }
        return bestMatch;
    }

    return substring;
}
于 2014-07-24T13:22:08.647 回答