【发布时间】:2017-07-20 08:37:01
【问题描述】:
在我的项目中,我使用的是 UITextField,我必须将其用作 UISearchBar,因为当我开始输入 UITableView 时将打开并显示搜索字符串。
我有一个名为字典的 NSDictionary,看起来像
{
268 = "David b Augustat";
449 = "Rocky Balboa";
489 = "Test Aayush";
493 = "Mohit Driver";
494 = "Tst ";
495 = "Mohit DriverA";
496 = "Test Kailash Driver";
497 = "Pramod Sinha";
498 = "Tty Ffff";
}
还有两个 NSArray DrivernameArray 和 DriverIdArray,其中包含字典中的 name 和 id
当我在 tableview 中显示搜索结果时,按名称搜索工作正常并显示正确的结果,但与该名称关联的 id 不会随名称更新,它始终保持不变
我正在使用以下代码
NSDictionary *listing = [dict6 objectForKey:@"result"];
DriverNameArray = [listing valueForKey:@"full_name"];
DriverIdArray = [listing valueForKey:@"id"];
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
tempArray = [NSArray arrayWithArray:DriverNameArray];
//NSString *stringTovSearch = textField.text;
tempId = [NSArray arrayWithArray:DriverIdArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@",driverTf.text]; // if you need case sensitive search avoid '[c]' in the predicate
NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
if (tempresults.count > 0)
{
tempArray = [NSArray arrayWithArray:tempresults];
tempId = [NSArray arrayWithArray:tempresults];
}
[SEarchTable reloadData];
return YES;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: nil];
}
cell.textLabel.font=[UIFont fontWithName: @"Arial" size: 14.0 ];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
{
UILabel * idlbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 10)];
[cell.contentView addSubview:idlbl];
idlbl.hidden = false;
if (tempArray.count > 0)
{
cell.textLabel.text = [tempArray objectAtIndex:indexPath.row];
idlbl.text = [DriverIdArray objectAtIndex:indexPath.row];
cell.textLabel.font=[UIFont fontWithName: @"Arial" size: 14.0 ];
}
else
{
idlbl.text = [DriverIdArray objectAtIndex:indexPath.row];
cell.textLabel.text = [DriverNameArray objectAtIndex:indexPath.row];
}
}
return cell;
}
【问题讨论】:
-
您需要合并数组 id 和名称,然后过滤该数组。
标签: ios objective-c iphone uitableview uisearchbar