IOS:搜索栏在tableview中

问题描述:

我创建的实现代码如下一个搜索栏,但我有这个方法的委托问题,因为我填补另一个数组内部数组表视图......我告诉我的代码:IOS:搜索栏在tableview中

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
ProgramAppDelegate *appDelegate = (ProgramAppDelegate *)[[UIApplication sharedApplication] delegate]; 
[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 appDelegate.globalArray) 
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 
    NSRange r = [name rangeOfString:searchText]; 
    if(r.location != NSNotFound) 
    { 
     if(r.location== 0)//that is we are checking only the start of the names. 
     { 
      [tableData addObject:name]; 
     } 
    } 
    counter++; 
    [pool release]; 
} 
[myTableView reloadData]; 
} 

你可以看到代码“for(NSString * name in appDelegate.globalArray)”它不起作用,因为我用这个全局数组内的数组元素填充表视图,我做了一个例子

在我的一排表视图有一个uitableviewcell,里面有四个标签; 我写这些标签与此globalArray的字符串,但以这样的方式

[cell.label1 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:1]]; 
[cell.label2 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:2]]; 
[cell.label3 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:3]]; 
[cell.label4 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:4]]; 

然后在搜索栏委托方法的代码“的(在appDelegate.globalArray的NSString *名称)”不工作,我怎样才能改变我的代码?

* *我就不多说了,我想只检查LABEL1的搜索

这里的问题是,globalArray是一个数组的数组。所以循环应该是这样的。

for(NSArray *rowArray in appDelegate.globalArray) 
{ 
    for (NSString *name in rowArray) { 
     // Do your processing here.. 
    } 
} 

使用tableData

在你tableView:cellForRowAtIndexPath:,做到这一点

[cell.label1 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:1]]; 
[cell.label2 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:2]]; 
[cell.label3 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:3]]; 
[cell.label4 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:4]]; 

在你numberOfSectionsInTableView:return 1;

在你tableView:numberOfRowsInSection:return [tableData count];

你应该包括将在用户停止搜索的搜索数据恢复到初始的内容的方法。

- (void)resetSearchData { 
    // Get appDelegate first. 

    self.tableData = [NSArray arrayWithArray:appDelegate.globalArray]; 
} 
+0

现在没有任何问题,但不搜索,当我写的内部搜索栏的名称,内容留在泰伯维 – CrazyDev 2011-05-30 09:01:50

+0

同样在这里有两件事情 - '[资料表ADDOBJECT:名字]'应该是'[资料表ADDOBJECT: rowArray];'你应该在'tableView:cellForRowAtIndexPath:'方法中用'tableData'替换'appDelegate.globalArray'。 – 2011-05-30 09:04:29

+0

第一件事就行了;第二件事我在loadview中做到这一点:[tableData addObjectsFromArray:appDelegate.globalArray]; – CrazyDev 2011-05-30 09:11:28