使用searchBar搜索单词的首字母

时间:2013-06-27 13:51:19

标签: iphone ios search uisearchbar

在我的应用中,我的联系人列表页面tableview中有一个搜索栏。现在,即使搜索文本位于名字或姓氏的中间,我的代码也会根据任何字母搜索列表。但我希望它只从头开始搜索。例如,“sh”这个词应该只拉“Shiva”,“Sheela”等,而不是“sathish”,“suresh”等等,任何人都可以帮我这个吗?

我的代码是

- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText
{
//---if there is something to search for---
if ([searchText length] > 0)
{
    isSearchOn = YES;
    canSelectRow = YES;
    self.ContactTableview.scrollEnabled = YES;
    searchTextValue = searchText;
    [searchResult removeAllObjects];

    for (NSString *str in ContactArray)
    {
        NSRange range = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if(range.location != NSNotFound)
        {
            if(range.length > 0)//that is we are checking only the start of the names.
            {
                [searchResult addObject:str];
            }
        }
    }
}
else
{
    //---nothing to search---
    isSearchOn = NO;
    canSelectRow = NO;
    self.ContactTableview.scrollEnabled = YES;
    //SearchBar.showsCancelButton = NO;
    [TitleBarLabel setText:@"All Contacts"];

}
[ContactTableview reloadData];
}

1 个答案:

答案 0 :(得分:2)

尝试使用谓词,在下面的代码中替换你的值。

 NSPredicate *p = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@",@"A"];
    NSArray *a = [NSArray arrayWithObjects:@"AhfjA ", @"test1", @"Test", @"AntA", nil];
    NSArray *b = [a filteredArrayUsingPredicate:p];
    NSLog(@"--%@",b);

O / P: -

(
    AntA,
    AntA
)