我想搜索以特定字母开头的所有名称,这意味着当我在搜索栏中输入一个字符时,它将显示以该字符开头的所有名称,但遗憾的是它还会显示包含该字符的名称。我想要仅显示以我在搜索栏中键入的特定字符开头的名称。请告诉我解决方案。
- (void)searchBar:(UISearchBar *)searchBars textDidChange:(NSString *)search
{
if(search.length == 0)
{
isFiltered = FALSE;
}
else{
isFiltered=true;
itemData =[[NSMutableArray alloc] init];
for (Item *itemsearch in listOfItemForStock) {
NSString *stringId = [NSString stringWithFormat:@"%i",itemsearch.iditem];
NSString *stringName = [NSString stringWithFormat:@"%@",itemsearch.name];
NSRange idRange = [stringId rangeOfString:search options:(NSCaseInsensitiveSearch)];
NSRange nameRange = [stringName rangeOfString:search options:(NSCaseInsensitiveSearch)];
if(idRange.location!=NSNotFound || nameRange.location != NSNotFound){
[self.itemData addObject:itemsearch];
}
}
}
[self.tableView reloadData];
}
答案 0 :(得分:2)
将名称检查更改为前缀检查。将nameRange变量替换为BOOL,该BOOL仅指示stringName是否以搜索字符串...
开头/// ...
BOOL nameMatches = [[stringName lowercaseString] hasPrefix:[search lowercaseString]];
if(idRange.location!=NSNotFound || nameMatches){
//..
答案 1 :(得分:0)
if(idRange.location!= NSNotFound || nameRange.location!= NSNotFound){
NSComparisonResult result = [itemsearch.name compare:search options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [search length])];
NSComparisonResult resultId = [[NSString stringWithFormat:@"%i",itemsearch.iditem ] compare:search options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [search length])];
if (result == NSOrderedSame || resultId == NSOrderedSame){
[self.itemData addObject:itemsearch];
}
}