我想暗示一个功能,例如当我单击搜索字段时,我需要在搜索字段下显示条件列表。根据我需要搜索的条件。如何将此列表添加到搜索字段。提前谢谢。
为了在SearchField
中动态显示列表,您必须首先将searchfield
的outlet
拖放到window
中,然后将searchfield
的委托连接到fileowners
一旦完成,则在代码下方插入元素:-
在下面的代码中,它包含一个元素数组,如果您在搜索字段中输入任何长度大于 3 的单词,那么它将根据array
中的匹配单词显示结果列表。
-(void)controlTextDidChange:(NSNotification *)obj
{
NSArray *filterArray=@[@"item1",@"item2",@"item3",@"item4",@"test1",@"test2",@"test3",@"test4",@"test5"];
NSString *searchString = [self.searchField stringValue];
NSMenu *menu= [[NSMenu alloc] initWithTitle: @"results"];
if (searchString.length>3)
{
NSArray *filteredArray = [filterArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF like %@", [searchString stringByAppendingString:@"*"]]];
for (NSString *addMenuItem in filteredArray)
{
[menu addItemWithTitle: addMenuItem action: @selector(someAction:) keyEquivalent: @""];
}
NSEvent *event = [NSEvent otherEventWithType: NSApplicationDefined
location: [self.searchField frame].origin
modifierFlags: 0
timestamp: 0
windowNumber: [[self.searchField window] windowNumber]
context: [[self.searchField window] graphicsContext]
subtype: NSAppKitDefined
data1: 0
data2: 0];
[NSMenu popUpContextMenu: [menu autorelease] withEvent: event forView: self.searchField];
}
}
-(void)someAction:(id)sender
{
//if you want to perform some action write here
}