Xcode IOS:tableview中的搜索栏
我正在tableview中创建搜索栏,但此方法委托有问题,因为我在另一个数组中用数组填充了table view…我显示了我的代码:Xcode IOS:tableview中的搜索栏,xcode,ios,uitableview,uisearchbar,Xcode,Ios,Uitableview,Uisearchbar,我正在tableview中创建搜索栏,但此方法委托有问题,因为我在另一个数组中用数组填充了table view…我显示了我的代码: - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { ProgramAppDelegate *appDelegate = (ProgramAppDelegate *)[[UIApplication sharedApplication] delegate];
- (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(appDelegate.globalArray中的NSString*name)”它不起作用,因为我用这个全局数组中的数组元素填充了表视图,我举了一个例子
在我的表格视图的一行中有一个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]];
然后,在搜索栏的委托方法中,代码“for(appDelegate.globalArray中的NSString*name)”不起作用,如何更改代码
**我并不是说我只想检查LABEL1进行搜索这里的问题是
globalArray
是一个数组数组。所以循环应该是这样的
for(NSArray *rowArray in appDelegate.globalArray )
{
for ( NSString *name in rowArray ) {
// Do your processing here..
}
}
使用表格数据
在表视图:cellforrowatinexpath:
中,执行以下操作
[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]];
在您的numberofsectionsintable视图中:
,返回1
在表格视图:numberofrowsin部分:
,返回[表格数据计数]代码>
您应该包括一种方法,当用户停止搜索时,该方法将把搜索数据重置为原始内容
- (void)resetSearchData {
// Get appDelegate first.
self.tableData = [NSArray arrayWithArray:appDelegate.globalArray];
}
现在没有问题,但不进行搜索,当我在搜索栏中写入名称时,TableView中的元素保持不变这里有两件事-[tableData addObject:name]
应该是[tableData addObject:rowArray]
并且您应该在tableView:cellForRowAtIndexPath:
方法中将appDelegate.globalArray
替换为tableData
;在loadview中执行此操作的第二件事:[tableData addObjectsFromArray:appDelegate.globalArray]<当控制器的view属性设置为nil时,仅调用一次code>loadView
。因此,它在过滤结果中的作用很小。我不明白当您将搜索结果保存在tableData
中时,为什么要从appDelegate.globalArray
加载数据。那么我该怎么办?你该怎么办?