UISearchBar 搜索框
///在 .h 寫代理 <UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate> ///結合UITableView 展示了UISearchBar_searchArray = [[NSMutableArray alloc] init]; _dataArray = [[NSMutableArray alloc] initWithObjects:@"qq", @"tencent", @"NOKIA", @"samsung", @"google", @"apple", @"MicroSoft", @"htc", nil];
_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 460) style:UITableViewStylePlain]; _tableView.delegate = self; _tableView.dataSource = self; [self.view addSubview:_tableView]; [_tableView release]; UISearchBar* searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 84)]; _tableView.tableHeaderView = searchBar; //類型 //searchBar.barStyle = UIBarStyleBlack; //占位符 searchBar.placeholder = @"請輸入搜索內容"; //副標題 //searchBar.prompt = @"這是什么?"; //顯示按鈕 searchBar.showsBookmarkButton = YES; searchBar.showsCancelButton = YES; searchBar.showsSearchResultsButton = YES; searchBar.showsScopeBar = YES; [searchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"a", @"b", @"c", @"d",nil]]; //設置代理 searchBar.delegate = self; - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{ NSArray* array = [NSArray arrayWithObjects:@"a", @"b", @"c", @"d",nil]; NSString* str = [array objectAtIndex:selectedScope]; searchBar.text = str;
}
//搜索
(void)searchBar:(UISearchBar )searchBar textDidChange:(NSString )searchText{ //如果搜索欄為空,代表我們沒有在搜索,tableView需要顯示原數據。如果不為空,代表我們在搜索,tableView要顯示搜索結果 if (searchBar.text == nil || [searchBar.text isEqualToString:@""]) {
_isSearch = NO;
} else {
_isSearch = YES; [_searchArray removeAllObjects]; for (NSString* str in _dataArray) { //判斷str里面是否包含searchBar.text NSRange range = [str rangeOfString:searchBar.text]; if (range.location != NSNotFound) { [_searchArray addObject:str]; } }
} [_tableView reloadData]; }
(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ [searchBar resignFirstResponder]; }
//tableView delegate
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ if (_isSearch) {
return _searchArray.count;
} return _dataArray.count; }
(UITableViewCell)tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath )indexPath{ UITableViewCell cell = [tableView dequeueReusableCellWithIdentifier:indexPath.row%2==0?@"IDRed":@"IDBlue"]; if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indexPath.row%2==0?@"IDRed":@"IDBlue"] autorelease]; if (indexPath.row%2 == 0) { cell.contentView.backgroundColor = [UIColor redColor]; } else { cell.contentView.backgroundColor = [UIColor blueColor]; }
}
if (_isSearch) {
cell.textLabel.text = [_searchArray objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [_dataArray objectAtIndex:indexPath.row];
}
return cell;
}</pre>