我有一个UISearchBar来搜索tableView中的一些数据,然后在搜索之后选择一行来打开detailViewController。要做到这一点,行必须保留索引路径,并且在搜索后不要更改初始indexPath,否则我无法在数据库中找到正确的元素。如何保留初始indexPath?还有其他方法吗?
-(void) searchExpositorsTableView{
[searchResult removeAllObjects];
//In this array there are the elements resulted after research
for (Database *currow in self.mutableArray){
NSLog(@"list of expositors %@", self.mutableArray);
NSRange titleResultsRange = [currow.name rangeOfString:self.searchBar.text options: NSCaseInsensitiveSearch];;
if (titleResultsRange.length >0) {
[searchResult addObject:currow.name];
/*While I build this new array every indexPath change and the database
can not track down the original items*/
}
}
NSLog(@"%@", searchResult);
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(canSelectRow){
NSLog(@"%d", indexPath.row);
/*the indexPath is new and the database can not track down the original items*/
return indexPath;
}else{
return nil;
}
NSLog(@"%d", indexPath.row);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//Open wrong element
}
答案 0 :(得分:1)
做这个
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if(searching) // where searching is boolean YES is searching, NO if not searched any element
{
//get your data from searchResults and open detailViewController
Database *currow = [searchResults objectAtIndex:indexPath.row];
DetailViewController = detailView = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
[self.navigationController pushViewController:detailView animated:YES];
[detailView release];
}
else
{
//get your data from self.mutableArray and open detailViewController
Database *currow = [self.mutableArray objectAtIndex:indexPath.row];
DetailViewController = detailView = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
[self.navigationController pushViewController:detailView animated:YES];
[detailView release];
}
}
答案 1 :(得分:1)
您可能在表视图数据方法中传递searchResult数组以生成搜索研究表视图,在这种情况下,您的表视图indexpath.row和searchResult数组中的对象索引必须相同:所以使用以下
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(canSelectRow){
NSString * name = [searchResult objectAtIndex:indexPath.row] ;
/*
or you should instead save the Database object in searchResult Array directly instead of currow.name , in that case
Database *currow = [searchResult objectAtIndex:indexPath.row] ;
*/
}else{
return nil;
}
NSLog(@"%d", indexPath.row);
}
答案 2 :(得分:0)
您应该使用cell标记来识别。在cellForRowAtIndexPath
中使用此代码 cell.tag = indexPath.row;
然后返回indexpath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
int ind = [tableView cellForRowAtIndexPath:indexPath].tag;
//now you have real indexpath
}