Adding a Search Bar to a UITableView


/ Published in: Objective C
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. //Add the search bar delegate to the header file
  2. <UISearchBarDelegate>
  3.  
  4. //Declare this in the header file.
  5. UISearchBar *searchBar;
  6. UISearchDisplayController *searchDC;
  7.  
  8.  
  9.  
  10.  
  11. // Create a search bar - you can add this in the viewDidLoad
  12. self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
  13. self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
  14. self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
  15. self.searchBar.keyboardType = UIKeyboardTypeAlphabet;
  16. self.searchBar.delegate = self;
  17. self.tableView.tableHeaderView = self.searchBar;
  18.  
  19. // Create the search display controller
  20. self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease];
  21. self.searchDC.searchResultsDataSource = self;
  22. self.searchDC.searchResultsDelegate = self;
  23.  
  24.  
  25.  
  26. //Then add this to your fetch or query method
  27. #pragma mark -
  28. #pragma mark Fetch Objects
  29.  
  30. - (void) fetchObjects
  31. {
  32. // Create a basic fetch request
  33. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  34. [fetchRequest setEntity:[NSEntityDescription entityForName:@"Venue" inManagedObjectContext:MANAGED_OBJECT_CONTEXT]];
  35.  
  36. // Add a sort descriptor
  37. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:nil];
  38. NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
  39. [fetchRequest setSortDescriptors:descriptors];
  40. [sortDescriptor release];
  41.  
  42. // Recover query
  43. NSString *query = self.searchBar.text;
  44. if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", query];
  45.  
  46. // Init the fetched results controller
  47. NSError *error;
  48. self.results = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:MANAGED_OBJECT_CONTEXT sectionNameKeyPath:@"section" cacheName:@"Root"];
  49. self.results.delegate = self;
  50. if (![[self results] performFetch:&error]) NSLog(@"Error: %@", [error localizedDescription]);
  51.  
  52. [self.results release];
  53. [fetchRequest release];
  54.  
  55. //[self.tableView reloadData];
  56. }

URL: http://www.espinallab.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.