demo下載:http://www.oschina.net/code/snippet_661032_15006 數組
- (void)viewDidLoad { //去除SearchBar的背景 [[_searchBarOf_Ready.subviews objectAtIndex:0] setHidden:YES]; [[_searchBarOf_Ready.subviews objectAtIndex:0] removeFromSuperview]; for (UIView *subview in _searchBarOf_Ready.subviews) { if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) { [subview removeFromSuperview]; break; } } [super viewDidLoad]; //Do any additional setup after loading the view from its nib. }
1. .net
NSArray *dataList; NSMutableArray *showData;定義2個數組,showData用來搜索存放顯示的數據,dataList用來存放原始數據.
2.實現如下幾個代理方法 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_showData count]>0?[_showData count]:0; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *TableSampleIdentifier = @"TableSampleIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: TableSampleIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableSampleIdentifier]; } if (_showData != nil && _showData.count >0) { NSUInteger row = [indexPath row]; cell.textLabel.text = [_showData objectAtIndex:row]; } return cell; } - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText; { NSLog(@"%i",[_dataList count]); if (searchText!=nil && searchText.length>0) { self.showData= [NSMutableArray array]; for (NSString *tempStr in _dataList) { if ([tempStr rangeOfString:searchText options:NSCaseInsensitiveSearch].length >0 ) { [_showData addObject:tempStr]; NSLog(@"%d",[_showData count]); } } [_tableView reloadData]; } else { self.showData = [NSMutableArray arrayWithArray:_dataList]; [_tableView reloadData]; } } -(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { [self searchBar:self.searchBar textDidChange:nil]; [_searchBar resignFirstResponder]; } - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar { [self searchBar:self.searchBar textDidChange:nil]; [_searchBar resignFirstResponder]; }