IOS:使用UISearchbar自动完成搜索

时间:2013-08-21 05:43:35

标签: iphone ios autocomplete uisearchbar uisearchdisplaycontroller

我有NSMutableArray,其中包含文字字段。我想在UISearchBar内的用户类型时加载它们。最初我不想在用户开始输入之前加载所有文本字段。只有用户开始输入需要加载的第一个字母建议。有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

有许多逻辑,但我把我的逻辑放在这里:

NSMutableArray方法中将两个ViewDidLoad一个数组添加到另一个数组,例如,

self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:@"YorArrayList", nil]; // array no - 2 

[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array

并编写以下委托UISearchBar方法

- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText
{
        NSString *name = @"";
        NSString *firstLetter = @"";

    if (self.listOfTemArray.count > 0)
         [self.listOfTemArray removeAllObjects];

        if ([searchText length] > 0)
        {
                for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
                {
                        name = [self.ItemOfMainArray objectAtIndex:i];

                        if (name.length >= searchText.length)
                        {
                                firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
                                //NSLog(@"%@",firstLetter);

                                if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
                                {
                                    // strings are equal except for possibly case
                                    [self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
                                    NSLog(@"=========> %@",self.listOfTemArray);
                                }
                         }
                 }
         }
         else
         {
             [self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
         }

        [self.tblView reloadData];
}
}

Consol.

中的输出显示

此代码可能对您有所帮助。

答案 1 :(得分:0)

我认为最好的方法是构建自己的NSCompoundPredicate:

  NSString *nameVar = ...; //ex: smith m
    NSArray *names = ...; //ex: John Smith, Mary Smith

    NSArray *terms = [nameVar componentsSeperatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSMutableArray *subpredicates = [NSMutableArray array];

    for(NSString *term in terms) {
      if([term length] == 0) { continue; }
      NSPredicate *p = [NSPredicate predicateWithFormat:@"name contains[cd] %@", term];
      [subpredicates addObject:p];
    }

    NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
    [fetchController setPredicate:filter];

享受编码!