1

我想搜索以特定字母开头的所有名称,这意味着当我在搜索栏中键入一个字符时,它将显示以该字符开头的所有名称,但不幸的是它也显示包含该字符的名称。我只想显示那些以我在搜索栏中键入的特定字符开头的名称。请告诉我解决方案。

 - (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];

}

4

2 回答 2

2

将名称检查更改为前缀检查。将 nameRange 变量替换为仅指示 stringName 是否以搜索字符串开头的 BOOL...

/// ...
BOOL nameMatches = [[stringName lowercaseString] hasPrefix:[search lowercaseString]];

if(idRange.location!=NSNotFound || nameMatches){
    //..
于 2012-09-11T02:49:35.193 回答
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];
            }
        }
于 2012-09-11T02:43:00.357 回答