Reputation: 2446
Actually i have stored too many data in table view and now I want to found my data easily so I need a search bar. Can any one give me a little solution?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifire = @"CellIdentifire";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifire];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
Upvotes: 0
Views: 1127
Reputation: 10172
Follow these steps:
Use following code to search:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setShowsCancelButton:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//Remove all objects first.
[self searchTerm:searchText];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Cancel clicked");
searchBar.text = @"";
[searchBar resignFirstResponder];
[searchBar setShowsCancelButton:NO];
[self showAllData];// to show all data
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(@"Search Clicked");
[searchBar setShowsCancelButton:NO];
[searchBar resignFirstResponder];
[self searchTerm:searchBar.text];
}
-(void)showAllData {
//load all data in _tableViewDataSourceArray, and reload table
}
-(void)searchTerm : (NSString*)searchText
{
if (searchText == nil) return;
_tableViewDataSourceArray = //YOUR SEARCH LOGIC
[self.tableView reloadData];
}
Edit: In case you wanna create Search bar with code then, Initialize a search bar and pass it as headerView Of your table view, inside
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
Dont's forget to return height of view in
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
Upvotes: 2