在我的应用中,我正在使用UISearchBar
,用户将通过用户名搜索NSMutableArray
进行搜索。以下是我从NSMutableArray
- (void)searchTableList
{
NSString *searchString = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in contentList)
{
NSArray *array = [dictionary objectForKey:@"username"];
[searchArray addObject:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchString options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[filteredContentList addObject:sTemp];
}
}
以下是我如何配置UITableView
来显示搜索结果
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"SearchListTableViewCell";
NSMutableDictionary *dict=[contentList objectAtIndex:indexPath.row];
SearchListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SearchListTableViewCell" owner:nil options:nil];
cell = (SearchListTableViewCell*)[topLevelObjects objectAtIndex:0];
cell.backgroundColor=[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
// Configure the cell...
if (isSearching)
{
cell.friendName.text = [filteredContentList objectAtIndex:indexPath.row];
NSMutableArray *searchImageArray=[[NSMutableArray alloc]init];
for (NSDictionary *dictionary in contentList)
{
NSArray *imageArray=[dictionary objectForKey:@"thumbnail_path_150_150"];
NSLog(@"image arrayt is %@",imageArray);
[searchImageArray addObject:imageArray];
}
for (NSString *imageS in searchImageArray) {
NSRange title=[imageS rangeOfString:cell.friendName.text options:NSCaseInsensitiveSearch];
if (title.length>0) {
[filteredImage addObject:imageS];
}
}
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[filteredImage objectAtIndex:indexPath.row]];
url=[url stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
NSLog(@"filtered Image data %lu",(unsigned long)filteredImage.count);
NSLog(@"filtered content list data %lu",(unsigned long)filteredContentList.count);
}
else
{
cell.friendName.text =[dict objectForKey:@"username"];
NSString *url=[NSString stringWithFormat:@"%@/get_image?avatar=%@",BaseURL,[dict objectForKey:@"thumbnail_path_150_150"]];
url=[url stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:url]]];
[cell.friendProfileImage setImage:myImage];
}
return cell;
}
现在我想从NSMutableDictionary
获取搜索到的用户名的其余数据。这是我的字典。
(
{
jid = "hey@196.0.0.1";
"thumbnail_path_150_150" = "E\\path\\to\\getImage\\files\\heythumbnail";
username = hey;
},
{
jid = "tweety@196.0.0.1";
"thumbnail_path_150_150" = "E:\\path\\to\\getImage\\files\\tweetythumbnail";
username = tweety;
}
)
这里我想获取搜索到的用户的图像。如果用户搜索嘿,它必须在tableViewCell上显示"thumbnail_path_150_150"
="E\\path\\to\\getImage\\files\\heythumbnail";
此图像。我尝试使用我的代码来设置图像但是当两个用户具有相同名称时它会替换图像。就像一个用户是Ray而另一个用户是Blueray,那么它会改变两者的形象。我知道我写的太多了。但在这一点上我真的很困惑。请任何人帮助解决这个问题。
答案 0 :(得分:4)
应用NSPredicate
过滤数组,然后使用此数组填充tableView
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username contains[c] %@",_search_bar.text];
NSArray *filteredArray = [yourMainArray filteredArrayUsingPredicate:predicate];
NSLog(@"here is the filteredCandyArray%@",filteredCandyArray);
//set it to the array you use to fill the table
_dataSourceArray = _filteredCandyArray;
//go!
[_yourTable reloadData];
字符串比较默认情况下是变音符号和变音符号敏感的。您可以使用方括号内的关键字符c和d修改运算符,分别指定大小写和变音符号不敏感,例如firstName BEGINSWITH [cd] $ FIRST_NAME。
BEGINSWITH:左手表达式以右手表达式开头。 CONTAINS:左手表达式包含右手表达式。 ENDSWITH:左手表达式以右手表达式结束。 LIKE:左手表达式等于右手表达式:?和*被允许作为通配符,在哪里?匹配1个字符,*匹配0个或更多个字符。 匹配:左手表达式等于右手表达式。 或进一步的详细信息,请访问http://nshipster.com/nspredicate/
答案 1 :(得分:2)
最简单的方法是使用谓词,稍作修改,你的代码可能会有点像这样
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username == %@", @"ray"];
NSArray *searchedArray = [rootArray filteredArrayUsingPredicate:predicate];
上面的代码只会返回其中username是ray而不是Ray或RAY等的值
答案 2 :(得分:1)
我建议您使用Search Bar and Search Display Controller
而不是Search Bar
。
另请查看以下代码,它涵盖了您想要的所有内容。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
#pragma mark
#pragma mark - View Lifecycle
-(void)viewDidLoad
{
[super viewDidLoad];
NSDictionary *dic1 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1", @"India", @"IN", @"+91", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"2", @"Australia", @"AU", @"+61", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"3", @"New Zealand", @"NZ", @"+64", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"4", @"South Africa", @"SA", @"+27", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"5", @"England", @"EN", @"+44", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic6 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"6", @"Israel", @"IS", @"+972", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic7 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"7", @"Afghanistan", @"AF", @"+93", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic8 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"8", @"Ireland", @"IR", @"+353", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
NSDictionary *dic9 = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"9", @"China", @"CN", @"+86", nil] forKeys:[NSArray arrayWithObjects:@"CountryId", @"CountryName", @"CountryCode", @"ISDCode", nil]];
arrTotalCountries = [NSArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, dic6, dic7, dic8, dic9, nil];
}
#pragma mark
#pragma mark - UITableView delegate, datasource methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView == self.searchDisplayController.searchResultsTableView){
return [arrFilteredCountries count];
}
else{
return [arrTotalCountries count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:@"CellIdentifier%ld%ld",(long)indexPath.section,(long)indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *strShow = [NSString stringWithFormat:@"%@ (%@)",[dicCountry objectForKey:@"CountryName"],[dicCountry objectForKey:@"ISDCode"]];
cell.textLabel.text = strShow;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *dicCountry;
if (tableView == self.searchDisplayController.searchResultsTableView) {
dicCountry = [arrFilteredCountries objectAtIndex:indexPath.row];
} else {
dicCountry = [arrTotalCountries objectAtIndex:indexPath.row];
}
NSString *countryName = [dicCountry objectForKey:@"CountryName"];
NSString *CountryISDCode = [dicCountry objectForKey:@"ISDCode"];
[self showAlertWithTitle:countryName message:CountryISDCode];
}
#pragma mark
#pragma mark - Other method Implementation
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.CountryName BEGINSWITH[cd] %@) OR (SELF.ISDCode CONTAINS[cd] %@)", searchText, searchText];
arrFilteredCountries = [arrTotalCountries filteredArrayUsingPredicate:predicate];
}
-(void)showAlertWithTitle:(NSString *)title message:(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
#pragma mark
#pragma mark - UISearchbar controller delegate
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#pragma mark
#pragma mark - Memory management
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
还要添加评论以防万一,任何人都会陷入困境。我已经实现了这个并且它工作得很好。这是向表视图添加搜索功能的简短而最好的方法。