NSSearchField不断调用方法

时间:2012-05-17 01:27:56

标签: objective-c cocoa nstextfield nssearchfield

我创建了一个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

2 个答案:

答案 0 :(得分:6)

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

喜欢如此:

Sends Whole Search String

希望这有帮助!

答案 1 :(得分:1)

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