• 27th, Nov 2010

Table View Controller – SearchBar

iPhone Table View SearchBar

MovieSearchTableController.h

//  Created by Ignacio Pascual on 27/11/2010.
#import <UIKit/UIKit.h>

@class MovieSearchOverlayTableController;

@interface MovieSearchTableController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
	IBOutlet UITableView *uiTableView;
	IBOutlet UISearchBar *searchBar;
	NSMutableArray *listOfItems;
	NSMutableArray *searchListOfItems;
	BOOL searchingMode;
	BOOL allowSelect;
	MovieSearchOverlayTableController *overlayTableController;
}

- (void) searchTableView;
- (void) doneSearchTouched:(id)sender;

@property (nonatomic, retain) IBOutlet UITableView *uiTableView;
@property (nonatomic, retain) IBOutlet UISearchBar *searchBar;
@property (nonatomic, retain) NSMutableArray *listOfItems;
@property (nonatomic, retain) NSMutableArray *searchListOfItems;
@property (nonatomic, retain) MovieSearchOverlayTableController *overlayTableController;

@end

MovieSearchTableController.m

//  Created by Ignacio Pascual on 27/11/2010.

#import "MovieSearchTableController.h"
#import "MovieSearchOverlayTableController.h"
#import "ProjectPopcorn.h"

@implementation MovieSearchTableController

@synthesize uiTableView,searchBar,listOfItems,searchListOfItems,overlayTableController;

- (void)viewDidLoad {
    [super viewDidLoad];

	//Customizing Table View
    uiTableView.rowHeight = 45;

    uiTableView.backgroundColor = [UIColor purpleColor];
    uiTableView.separatorColor = [UIColor yellowColor];

	//Initialize the array.
	listOfItems = [[NSMutableArray alloc] init];

	NSArray *moviesBatch1Array = [NSArray arrayWithObjects:@"Paranormal Activity", @"Nine", @"Salvage", @"The Step Gather", nil];
	NSDictionary *moviesBatch1InDict = [NSDictionary dictionaryWithObject:moviesBatch1Array forKey:@"Movies"];

	NSArray *moviesBatch2Array = [NSArray arrayWithObjects:@"The Dark Night", @"Where the Wild things Are", nil];
	NSDictionary *moviesBatch2InDict = [NSDictionary dictionaryWithObject:moviesBatch2Array forKey:@"Movies"];

	[listOfItems addObject:moviesBatch1InDict];
	[listOfItems addObject:moviesBatch2InDict];

	//Initialize the search array
	searchListOfItems = [[NSMutableArray alloc] init];

	//Set the title
	self.navigationItem.title = @"On Cinemas";

	//Add the search bar
	self.tableView.tableHeaderView = searchBar;
	searchBar.autocorrectionType = UITextAutocorrectionTypeNo;

	searchingMode = NO;
	allowSelect = YES;
}

#pragma mark Table view methods

// Sections: number
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	if (searchingMode)
		return 1;
	else
		return [listOfItems count];
}

// Sections: style and data
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	UIView *tempView = [[[UIView alloc]initWithFrame:CGRectMake(0,0,300,30)]autorelease];
	tempView.backgroundColor = [UIColor grayColor];

	UILabel *tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(10,0,300,30)];
	tempLabel.backgroundColor = [UIColor clearColor];
	tempLabel.font = [UIFont boldSystemFontOfSize:14.0];
	tempLabel.textColor = [UIColor whiteColor];

	if(searchingMode) {
		tempLabel.text=@"Search Results";
	}
	else{
		if(section == 0)
			tempLabel.text=@"24 April 2010";
		else
			tempLabel.text=@"19 April 2010";
	}

	[tempView addSubview:tempLabel];
	[tempLabel release];

	return tempView;
}

// Sections: height
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 30;
} 

// Cell: number of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

	if (searchingMode)
		return [searchListOfItems count];
	else {
		//Number of rows it should expect should be based on the section
		NSDictionary *dictionary = [listOfItems objectAtIndex:section];
		NSArray *array = [dictionary objectForKey:@"Movies"];
		return [array count];
	}
}

// Cell: style and data
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		//Single Cell
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
		// or with detail text
		//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
	}

	// Set up the cell
	cell.textLabel.textColor = [UIColor whiteColor];
	cell.textLabel.font = [UIFont boldSystemFontOfSize:12.0];
	// Set up the detail text
	//cell.detailTextLabel.textColor = [UIColor grayColor];
	//cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:13.0];
    //cell.detailTextLabel.textAlignment = UITextAlignmentCenter;

	// Set the text
	if(searchingMode)
		cell.text = [searchListOfItems objectAtIndex:indexPath.row];
	else {

		//First get the dictionary object
		NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
		NSArray *array = [dictionary objectForKey:@"Movies"];
		NSString *cellValue = [array objectAtIndex:indexPath.row];
		cell.text = cellValue;
	}

	return cell;
}

// Cell: didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//Push Detail View Controller...
}

// Cell: willSelectRowAtIndexPath
- (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if(allowSelect)
		return indexPath;
	else
		return nil;
}

// Cell: accessoryTypeForRowWithIndexPath
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellAccessoryDisclosureIndicator;
}

// Cell: accessoryButtonTappedForRowWithIndexPath
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	[self tableView:tableView didSelectRowAtIndexPath:indexPath];
}

#pragma mark -

#pragma mark Search Bar 

// SearchBar: searchBarTextDidBeginEditing
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {

	if(searchingMode)
		return; // If it's called again

	// Add the overlay view
	if(overlayTableController == nil)
		overlayTableController = [[MovieSearchOverlayTableController alloc] initWithNibName:@"MovieSearchOverlayTableView" bundle:[NSBundle mainBundle]];

	CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
	CGFloat width = self.view.frame.size.width;
	CGFloat height = self.view.frame.size.height;

	//Parameters x = origion on x-axis, y = origon on y-axis.
	CGRect frame = CGRectMake(0, yaxis, width, height);

	overlayTableController.view.frame = frame;
	overlayTableController.view.backgroundColor = [UIColor grayColor];
	overlayTableController.view.alpha = 0.5;

	overlayTableController.rootController = self;

	[self.tableView insertSubview:overlayTableController.view aboveSubview:self.parentViewController.view];

	searchingMode = YES;
	allowSelect = NO;
	self.tableView.scrollEnabled = NO;

	//Add the done button.
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
											   initWithBarButtonSystemItem:UIBarButtonSystemItemDone
											   target:self action:@selector(doneSearchTouched:)] autorelease];
}

// SearchBar: textDidChange
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {

	//Remove all objects first.
	[searchListOfItems removeAllObjects];

	if([searchText length] > 0) {
		[overlayTableController.view removeFromSuperview];
		searchingMode = YES;
		allowSelect = YES;
		self.tableView.scrollEnabled = YES;
		[self searchTableView];
	}
	else {
		[self.tableView insertSubview:overlayTableController.view aboveSubview:self.parentViewController.view];
		searchingMode = NO;
		allowSelect = NO;
		self.tableView.scrollEnabled = NO;
	}

	[self.tableView reloadData];
}

// SearchBar: search bar clicked
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {

	[self searchTableView];
}

// SearchBar: search method
- (void) searchTableView {

	NSString *searchText = searchBar.text;
	NSMutableArray *searchArray = [[NSMutableArray alloc] init];

	for (NSDictionary *dictionary in listOfItems)
	{
		NSArray *array = [dictionary objectForKey:@"Movies"];
		[searchArray addObjectsFromArray:array];
	}

	for (NSString *sTemp in searchArray)
	{
		NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

		if (titleResultsRange.length > 0)
			[searchListOfItems addObject:sTemp];
	}

	[searchArray release];
	searchArray = nil;
}

// SearchBar: finish search
- (void) doneSearchTouched:(id)sender {

	searchBar.text = @"";
	[searchBar resignFirstResponder];

	allowSelect = YES;
	searchingMode = NO;
	self.navigationItem.rightBarButtonItem = nil;
	self.tableView.scrollEnabled = YES;

	[overlayTableController.view removeFromSuperview];
	[overlayTableController release];
	overlayTableController = nil;

	[self.tableView reloadData];
}

#pragma mark -

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[overlayTableController release];
	[searchListOfItems release];
	[searchBar release];
	[listOfItems release];
    [super dealloc];
}

@end

MovieSearchOverlayTableController.h

//  Created by Ignacio Pascual on 27/11/2010.

#import <UIKit/UIKit.h>
#import "MovieTableController.h"

@interface MovieSearchOverlayTableController : UIViewController {
	MovieTableController *rootController;
}

@property (nonatomic, retain) MovieTableController *rootController;

@end

MovieSearchOverlayTableController.m

//  Created by Ignacio Pascual on 27/11/2010.

#import "MovieSearchOverlayTableController.h"

@implementation MovieSearchOverlayTableController

@synthesize rootController;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

	[rootController doneSearchTouched:nil];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[rootController release];
    [super dealloc];
}

@end

xCode Interface Builder for MovieTableSearchView

xCode Interface Builder for MovieTableOverlaySearchView

TAGS: None

3 Responses to “Table View Controller – SearchBar”


  1. ruben
    on Jan 11th, 2011
    @ 4:24 am

    Hello thanks for the tutorial, but I would like to do that when I select a cell loads a Web instead of to put text and if I select another different cell loads another different Web, I have few knowledge I have been two months trying to learn and I would like if you could give a version me as I say to you, thanks I wait for answer


  2. admin
    on Jan 21st, 2011
    @ 12:19 am

    Use this code
    Hola Ruben,

    Try this code:
    NSString *url = [[NSString alloc] initWithFormat: @"http://www.dontask-dontget.co.uk/signup/",session.profileId];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString: [url stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]]];

    …in the method

    (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ...


  3. ruben
    on Jan 23rd, 2011
    @ 1:19 am

    thanks for the answer, but my knowledge are few, gives an error me “session undeclared”

Leave a Reply

*

© 2010 unexpected[it]. All Rights Reserved.