2011-05-02 58 views
1

的tableView好,所以我正在实施一个UISearchBar在一个tableView有章节。这可能是错的,但填充表查看第一次,我也有很多条目的数组,然后填充像这样的内容:如何使用UISearchBar与具有部分

if(indexPath.section ==0){ 

      [cell.textLabel setText:[tableData objectAtIndex:indexPath.row]];     
    }else if(indexPath.section ==1){ 

      [cell.textLabel setText:[tableData objectAtIndex:indexPath.row+4]];      
    }else if(indexPath.section ==2){ 

      [cell.textLabel setText:[tableData objectAtIndex:indexPath.row+8]];      
    } 

中远离优雅,但它的工作原理。现在,我试图来装的UISearchBar,这是我遇到的问题与方法:

- (void)searchBar:(UISearchBar *)sBar textDidChange:(NSString *)searchText 
    { 
[tableData removeAllObjects];// remove all data that belongs to previous search 
if([searchText isEqualToString:@""] || searchText==nil){ 
    [tableView reloadData]; 
    return; 
} 
NSInteger counter = 0; 
for(NSString *name in dataSource) 
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 
    NSRange r = [name rangeOfString:searchText]; 
    if(r.location != NSNotFound) 
    { 

      [tableData addObject:name]; 

    } 

    [pool release]; 
} 

[tableView reloadData]; 
    } 

所以我提出再一个数组,符合搜索条件的条目,但后来当我试图重新加载我的tableView,它得到所有的嘲弄,因为它期待部分。但我想要的只是一个简单的无段视图的结果。

我怎样才能实现这个UISearchBar与部分的tableView?

感谢

+0

为不同部分保留不同的数组。 – Anish 2011-05-03 03:23:24

回答

0

设置,当你进入搜索和调整BOOL你的部分进行相应的计数

例如

在viewDidLoad中

BOOL isSearching = NO; 

设置为YES

,当你进入textDidChange方法。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    int t; 
if (isSearching) t = 1 
else { 
t= array.count; 
} 
return t; 
} 
0

你不需要保留另一个变量;只需询问tableView参数即可查看谁在询问部分的数量。例如,假设在fetchedResultsController你的数据是可用的:

if (tableView == self.searchDisplayDisplayController.searchResultsTableView) { 
     // your table is the search results table, so just return 1 
     return 1; 
    } else { 
     // your table is your "own" table 
     return [[self.fetchedResultsController sections] count]; 
    } 

我做同样的事情在我的很多表视图委托和数据源的方法。