UISearchBar 搜索两个数组
我有一个搜索栏,用于搜索数组,并用结果更新 UITableView。表格视图是书籍列表,包含标题和作者:
现在,搜索栏仅搜索标题,但我想让它也搜索作者。这是我的搜索代码(我从 http://blog.webscale.co 获得.in/?p=228)。
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""]||searchText==nil){
[tableView reloadData];
return;
}
for(NSString *name in dataSource){
NSInteger counter = 0;
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [[name lowercaseString] rangeOfString:[searchText lowercaseString]];
if(r.location != NSNotFound)
[tableData addObject:name];
counter++;
}
//[pool release];
[tableView reloadData];
dataSource
是包含标题的 NSMutable 数组。包含作者的数组称为“author”。 “tableData”是存储应出现在屏幕上的单元格(包含正在搜索的术语的单元格)的数组。
非常感谢,
卢克
I Have a search bar that searches an array, and updates a UITableView with the results. The table view is a list of books, with titles and authors:
Right now, the search bar only searches the titles but I would like to make it search the authors as well. Here is the search code I have (I got it from http://blog.webscale.co.in/?p=228).
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""]||searchText==nil){
[tableView reloadData];
return;
}
for(NSString *name in dataSource){
NSInteger counter = 0;
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [[name lowercaseString] rangeOfString:[searchText lowercaseString]];
if(r.location != NSNotFound)
[tableData addObject:name];
counter++;
}
//[pool release];
[tableView reloadData];
}
dataSource is the NSMutable Array that contains the titles. the array that contains the authors is called "author". "tableData" is the array that stores the cells that should appear on the screen (the cells that contain terms being searched for).
Thanks so much,
Luke
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将通过创建带有键值对的 NSDictionary 来修改 dataSource 数组以包含标题和作者(Book 类会更好)。
之后,您可以更改搜索方法以使用 NSDictionary。
请注意,使用此方法您将更改 cellForRowAtIndexPath 方法以使用 NSDictionary 而不是标题字符串。
I would modify the dataSource array to contain both the titles and authors by creating an NSDictionary with key value pairs (a Book class would be better).
After that you can change your search method to work with the NSDictionary instead.
Note using this method you would have the change your cellForRowAtIndexPath method to work with the NSDictionary and not the title strings.