如何动态地向搜索字段添加列表?

时间:2013-12-19 14:14:04

标签: objective-c cocoa search nssearchfield

我想要实现一种功能,例如当我点击搜索字段时,我需要在搜索字段下显示标准列表。根据我需要搜索的标准。如何将此列表添加到搜索字段。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

对于SearchField中动态显示的列表,您必须先在outlet中拖放searchfield window,然后再连接searchfield的代表到fileowners一旦完成,然后在代码下面的inslement: -

在下面的代码中,它包含一个元素数组,如果在搜索字段中输入长度大于3的任何单词,则它将根据array中的匹配单词显示结果列表。 / p>

-(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
}