5

在表格视图中,我设置了 UISearchBar、设置委托并添加协议。

当用户点击一个词时,除了“网球”的搜索与“网球”不同之外,一切都很好。

如何使搜索栏成为不区分大小写的 UISearchBar?这是我认为发生任何事情的代码:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
 [tableData removeAllObjects];// remove all data that belongs to previous search
 if([searchText isEqualToString:@""]||searchText==nil){
  [myTableView reloadData];
  return;
 }
 NSInteger counter = 0;
 for(NSString *name in dataSource)
 {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
  NSRange r = [name rangeOfString:searchText];
  if(r.location != NSNotFound)
   [tableData addObject:name];
  counter++;
  [pool release];
 }
 [myTableView reloadData];
}
4

4 回答 4

14

最简单的方法可能是

 NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
于 2010-03-16T23:46:51.067 回答
2

尝试这个。

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [DetailSearchArray removeAllObjects];// remove all data that belongs to previous search

    if([searchText isEqualToString:@""]){
        [table reloadData];
        return;
    }

    NSInteger counter = 0;
    NSArray *result = [[NSArray alloc] initWithArray:[resultArray filteredArrayUsingPredicate:predicate]];

    for (NSString *name in  resultArray  ) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
        //NSRange r=[name rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
        if(r.location != NSNotFound)
        {
            if(r.location== 0)//that is we are checking only the start of the names.
            {
                [DetailSearchArray addObject:name]; 
            }
        }

        }
        counter++;
        [pool release];
    }

    [table reloadData];
}
于 2010-11-15T08:59:14.160 回答
1

进行比较时,请尝试使用小写版本。

NSRange r = [[name lowercaseString] rangeOfString:[searchText lowercaseString]];

只是为了澄清一下,这不会改变任何值,只返回原始的小写版本,然后您可以使用它来进行比较,

于 2010-03-16T23:17:23.987 回答
0

Theres some 'lowercaseString' function, don't know where I came across this seeing as I have nothing to do with iPhones, I'm sure if you google it you'll find something.

于 2010-03-16T22:50:00.243 回答