4

我创建了一个NSSearchField存储最近搜索列表的列表。搜索字段连接到一种方法,该方法使用在搜索字段中键入的文本更新窗口中的标签。问题是标签会在用户输入搜索字段后立即更新,我需要标签在用户输入文本然后按 Enter 键后才更新。我可以用典型的来做到这一点,NSTextField但我想使用,NSSearchField所以我可以显示最近的搜索。请在下面查看我的代码并提供一些建议。谢谢。

接口文件:

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate>

@property (assign) IBOutlet NSWindow *window;

@property (weak) IBOutlet NSSearchField *searchField;
@property (weak) IBOutlet NSTextField *textField;

- (IBAction)searchString:(id)sender;

@end

实现文件:

#import "AppDelegate.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize searchField, textField;

- (void)awakeFromNib {

    if ( [searchField respondsToSelector:@selector(setRecentSearches:)] ) {
        NSMenu *searchMenu = [[NSMenu alloc] initWithTitle:@"Search Menu"];
        [searchMenu setAutoenablesItems:YES];

        NSMenuItem *recentsTitleItem = [[NSMenuItem alloc] initWithTitle:@"Recent Searches" action:nil keyEquivalent:@""];
        [recentsTitleItem setTag:NSSearchFieldRecentsTitleMenuItemTag];
        [searchMenu insertItem:recentsTitleItem atIndex:0];

        NSMenuItem *norecentsTitleItem = [[NSMenuItem alloc] initWithTitle:@"No recent searches" action:nil keyEquivalent:@""];
        [norecentsTitleItem setTag:NSSearchFieldNoRecentsMenuItemTag];
        [searchMenu insertItem:norecentsTitleItem atIndex:1];

        NSMenuItem *recentsItem = [[NSMenuItem alloc] initWithTitle:@"Recents" action:nil keyEquivalent:@""];
        [recentsItem setTag:NSSearchFieldRecentsMenuItemTag];   
        [searchMenu insertItem:recentsItem atIndex:2];

        NSMenuItem *separatorItem = (NSMenuItem*)[NSMenuItem separatorItem];
        [separatorItem setTag:NSSearchFieldRecentsTitleMenuItemTag];
        [searchMenu insertItem:separatorItem atIndex:3];

        NSMenuItem *clearItem = [[NSMenuItem alloc] initWithTitle:@"Clear" action:nil keyEquivalent:@""];
        [clearItem setTag:NSSearchFieldClearRecentsMenuItemTag];
        [searchMenu insertItem:clearItem atIndex:4];

        id searchCell = [searchField cell];
        [searchCell setMaximumRecents:20];
        [searchCell setSearchMenuTemplate:searchMenu];
    }
}

- (IBAction)searchString:(id)sender {
    [textField setStringValue:[searchField stringValue]];
}

@end
4

2 回答 2

6

如果您不想在代码中执行此操作,请查看您的 nib 文件,选择搜索字段并选择“发送整个搜索字符串”

像这样:

发送整个搜索字符串

希望这可以帮助!

于 2012-05-17T02:44:27.050 回答
1

您需要使用 [searchField.cell setSendsWholeSearchString:YES]

于 2012-05-17T02:38:34.217 回答