2011-05-02 57 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]; 
    } 

我做同樣的事情在我的很多表視圖委託和數據源的方法。