UISearch bar case insensitive?

我的梦境 提交于 2019-12-06 03:17:47

问题


In a table view I have set a UISearchBar, set the delegate, and add the protocol.

When user tap a word everything is okay except that the search of "tennis" is different from "Tennis".

How can I make the search bar a case-insensitive UISearchBar? Here is my code where I think evrything happens:

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

回答1:


The easiest way to do this is probably

 NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];



回答2:


Try this.

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



回答3:


When you do the comparison, try doing it with the lowercase version.

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

Just to clarify, this will not change any of the values, just return a lowercase version of the original, that you then use to do the comparison with,




回答4:


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.



来源:https://stackoverflow.com/questions/2458636/uisearch-bar-case-insensitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!