我创建了一个 NSSearchField
来存储最近搜索的列表。搜索字段连接到一个方法,该方法使用输入到搜索字段中的文本更新窗口中的标签。问题是标签在用户输入搜索字段后立即更新,我需要标签在用户输入文本然后点击 Enter 键后才更新。我可以用典型的 NSTextField
做到这一点,但我想使用 NSSearchField
以便我可以显示最近的搜索。请在下面查看我的代码并提供一些建议。谢谢。
接口(interface)文件:
#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
最佳答案
如果您不想在代码中执行此操作,请查看您的 nib 文件,选择搜索字段并选择“发送整个搜索字符串”
像这样:
希望这可以帮助!
关于objective-c - NSSearchField 不断调用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10628809/