/ Published in: Objective C

URL: http://www.espinallab.com
This might look complicated but actually it was easy than what I though to integrate. I'm using it with Core Data, but I'm sure you can use it with any data type.
Expand |
Embed | Plain Text
//Add the search bar delegate to the header file <UISearchBarDelegate> //Declare this in the header file. UISearchBar *searchBar; UISearchDisplayController *searchDC; // Create a search bar - you can add this in the viewDidLoad self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease]; self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo; self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone; self.searchBar.keyboardType = UIKeyboardTypeAlphabet; self.searchBar.delegate = self; self.tableView.tableHeaderView = self.searchBar; // Create the search display controller self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease]; self.searchDC.searchResultsDataSource = self; self.searchDC.searchResultsDelegate = self; //Then add this to your fetch or query method #pragma mark - #pragma mark Fetch Objects - (void) fetchObjects { // Create a basic fetch request [fetchRequest setEntity:[NSEntityDescription entityForName:@"Venue" inManagedObjectContext:MANAGED_OBJECT_CONTEXT]]; // Add a sort descriptor NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:nil]; [fetchRequest setSortDescriptors:descriptors]; [sortDescriptor release]; // Recover query if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query]; // Init the fetched results controller NSError *error; self.results = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:MANAGED_OBJECT_CONTEXT sectionNameKeyPath:@"section" cacheName:@"Root"]; self.results.delegate = self; if (![[self results] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]); [self.results release]; [fetchRequest release]; //[self.tableView reloadData]; }
Comments

You need to login to post a comment.
Thanks for the code on adding a Search Bar to a UITableView. Very helpful! I compiled a list of some top resources on this topic, and included your post. Hope other developers find this useful too. Check it out, feel free to share: http://www.verious.com/board/Giancarlo-Leonio/implementing-an-ios-search-bar-in-table-view/
Thank you