This is very simple SearchBar Application.In this application we will see how to SearchBar implement in the TableView
and the code. So let see how it will worked.
Step 1: Open the Xcode, Create a new project using Navigation Base application. Give the application “SearchBar”.
Step 2: Xcode automatically creates the directory structure and adds essential frameworks to it. You can explore the
directory structure to check out the content of the directory.
Step 3: Expand classes and notice Interface Builder created the RootViewController class for you. Expand Resources and
notice the template generated a separate nib, RootViewController.xib for the SearchBar application.
Step 4: We need to add one UIViewcontrollersub class in the application. Select New File -> Cocoa Touch -> select
UIViewcontrollersub. Give the class name”SearchView”.
Step 5: Open the RootViewController.h file and make the following changes in the file:
@interface RootViewController : UITableViewController {
NSMutableArray *data;
NSMutableArray *Listdata;
IBOutlet UISearchBar *searchBar;
BOOL search;
BOOL Rowselect;
}
– (void) search;
– (void) doneButtonClicked:(id)sender;
@end
Step 6: Double click the RootViewController.xib file and open it to the Interface Builder. First drag SearchBar from the
library and place it to the View window. Select SearchBar from the interface builder and bring up Connection
Inspector,connect delegate to file’s owner icon and File’s Owner icon to SearchBar and select “searchBar”. Now save
the .xib file save it, close it and go back to the Xcode.
Step 7: In the RootViewController.m file make the following changes in the file,
@implementation RootViewController
– (void)viewDidLoad
{
[super viewDidLoad];
data = [[NSMutableArray alloc] init];
NSArray *NameArray = [NSArray arrayWithObjects:@"Ambalika", @"Arti", @"Arun", @"Balen",
@"Chandrani", @"Chandrika", @"Deepak", @"Dilip",@"Emran",@"Era", nil];
NSDictionary *NameArrayInDict = [NSDictionary dictionaryWithObject:NameArray forKey:@"Names"];
[data addObject:NameArrayInDict];
Listdata = [[NSMutableArray alloc] init];
self.navigationItem.title =@" Names ";
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
search = NO;
Rowselect = YES;
}
#pragma mark Table view methods
– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (search)
return 1;
else
return [data count];
}
// Customize the number of rows in the table view.
– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (search)
return [Listdata count];
else {
NSDictionary *dictionary = [data objectAtIndex:section];
NSArray *array = [dictionary objectForKey:@"Names"];
return [array count];
}
}
– (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(search)
return @"Search Results";
if(section == 0)
return @"Search Names";
}
– (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title
atIndex:(NSInteger)index {
if(search)
return –1;
return index % 2;
}
– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)
indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]
autorelease];
}
if(search)
cell.textLabel.text = [Listdata objectAtIndex:indexPath.row];
else {
NSDictionary *dictionary = [data objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Names"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}
return cell;
}
– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *selectedCountry = nil;
if(search)
selectedCountry = [Listdata objectAtIndex:indexPath.row];
else
{
NSDictionary *dictionary = [data objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Names"];
selectedCountry = [array objectAtIndex:indexPath.row];
}
}
– (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)
indexPath {
if(Rowselect)
return indexPath;
else
return nil;
}
– (UITableViewCellAccessoryType)tableView:(UITableView *)tableView
accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellAccessoryDisclosureIndicator;
}
– (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath
*)indexPath
{
[self tableView:tableView didSelectRowAtIndexPath:indexPath];
}
#pragma mark –
#pragma mark Search Bar
– (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
if(search)
return;
search = YES;
Rowselect = NO;
self.tableView.scrollEnabled = NO;
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:@selector(DoneButton:)]
autorelease];
}
– (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
[Listdata removeAllObjects];
if([searchText length] > 0) {
search = YES;
Rowselect = YES;
self.tableView.scrollEnabled = YES;
[self search];
}
else {
search = NO;
Rowselect = NO;
self.tableView.scrollEnabled = NO;
}
[self.tableView reloadData];
}
– (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar
{
[self search];
}
– (void) search {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in data)
{
NSArray *array = [dictionary objectForKey:@"Names"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText
options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[Listdata addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
– (void) DoneButton:(id)sender {
searchBar.text = @"";
[searchBar resignFirstResponder];
Rowselect = YES;
search = NO;
self.navigationItem.rightBarButtonItem = nil;
self.tableView.scrollEnabled = YES;
[self.tableView reloadData];
}
– (void)dealloc
{
[Listdata release];
[searchBar release];
[data release];
[super dealloc];
}
@end
Step 8: Open the SearchView.h file and make the following changes in the file:
@class RootViewController;
@interface SearchView : UIViewController {
RootViewController *rootController;
}
@property (nonatomic, retain) RootViewController *rootController;
@end
Step 9: In the SearchView.m file make the following changes:
#import "RootViewController.h"
@implementation SearchView
@synthesize rootController;
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[rootController doneButtonClicked:nil];
}
– (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
– (void)dealloc
{
[super dealloc];
[rootController release];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark – View lifecycle
– (void)viewDidLoad
{
[super viewDidLoad];
}
– (void)viewDidUnload
{
[super viewDidUnload];
}
– (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
Step 10: Now Compile and run the application in the Simulator.
You can Download SourceCode from here Search Bar Source Code.