5. Search Bars
Search bars gather user input and allow applications to respond to
that input in real time. A simple example is using a search bar at the top of the
screen to filter a list of records in a table view based on string
pattern matching. To use a search bar, you must create an instance of
UISearchBar and add it to your view. You must also
set the delegate property of the
UISearchBar instance to an object that implements the
UISearchBarDelegate protocol. Each method in the
UISearchBarDelegate protocol handles a different user
action. For example, you can implement the searchBar:textDidChange: method to
develop progressive searches (a.k.a., auto-complete searches), or you
can choose to execute searches only when editing ends using the
searchBarSearchButtonClicked: and
searchBarTextDidEndEditing:
methods.
The TileSearchViewController class is from
an example application that filters colored tiles based on color names
input by a user:
#import "TileSearchViewController.h"
#import "Board.h"
@implementation TileSearchViewController
- (void)viewDidLoad
{
searchBar = [[UISearchBar alloc]
initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
searchBar.showsCancelButton = NO;
// Set myself as the delegate of the search bar.
searchBar.delegate = self;
[self.view addSubview:searchBar];
if(board == nil) board = [[Board alloc]
initWithFrame:CGRectMake(0.0, 45.0, 320.0, 415.0)];
[self.view addSubview:board];
}
#pragma mark UISearchBarDelegate methods
- (void)searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar
{
// Show cancel button while editing
searchBar.showsCancelButton = YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)theSearchBar
{
// Hide cancel button when editing ends
searchBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)theSearchBar
textDidChange:(NSString *)searchText
{
[board filterForColorName:searchText];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)theSearchBar
{
// Repopulate the last color unless the user cleared the search
if (theSearchBar.text.length > 0){
searchBar.text = lastSearch;
}else{
searchBar.text = @"";
}
[searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)theSearchBar
{
[lastSearch release];
lastSearch = [theSearchBar.text copy];
[searchBar resignFirstResponder];
}
- (void)dealloc
{
[searchBar release];
[board release];
[lastSearch release];
[super dealloc];
}
@end
Figure 9 shows a screenshot of the
TileSearch example application.