How to use UISearchBar with TableView in iOS
If we have a huge list of items and want to search a item from the list then we use the UISearchBar with TableView and the item will be displayed in the table which have the matching value with the search text .
Here are the steps:
Step1: Add UITableView to the main.storyboard.
Step2: set the delegate and dataSource for the tableView
Step3: Create the outlet fot tableView with following Syntax __weak IBOutlet UITableView *myTableView;
Step 4: add the UISearchBar to main.storyboard.
Step 5:set the delegate for the searchBar.
Step 5: map the myTableView with TableView.
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
__weak IBOutlet UITableView *myTableView;
NSMutableArray *stateArray;
NSMutableArray *tempArray;
}
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
stateArray = [[NSMutableArray alloc]initWithObjects:@"Rajasthan", @"Uttar Pradesh", @"Uttarakhand",@"West Bengal",@"Tamil Nadu",@"Sikkim",@"Gujarat",@"Haryana",@"Himachal Pradesh",@"Karnataka", nil];
tempArray = [[NSMutableArray alloc]init];
for (id object in stateArray) {
[tempArray addObject:object];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - TableMethods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [tempArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cellIdentifier = @"MyTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [tempArray objectAtIndex:indexPath.row];
return cell;
}
# pragma Delegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
//called when text starts editing
{
NSLog(@"Editing bigin\n\n");
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tempArray removeAllObjects];
if (searchText.length) {
for (NSString *string in stateArray) {
NSRange range = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.length) {
[tempArray addObject:string];
}
}
}
else{
[tempArray addObjectsFromArray:stateArray];
}
[myTableView reloadData];
}
@end
0 Comment(s)