Pour ajouter une UISearchBar à un UITableView, il faut procéder comme suit :
- Déclarer et initialiser UISearchBar
- Déclarer et initialiser le UISearchDisplayController
- Ajouter la barre de recherche à la tableView
- Implémenter le délégué UISearchDisplayController
- Dans le fichier d'en-tête, je déclare ma searchBar, mon searchDisplayController et les tableaux qui contiennent les données à afficher.
ViewController.h :
#import
@interface ViewController : UITableViewController
{
NSArray *originalData;
NSMutableArray *searchData;
UISearchBar *searchBar;
UISearchDisplayController *searchDisplayController;
}
@end
J'ai également ajouté 2 délégués à la classe : UISearchBarDelegate et UISearchDisplayDelegate, sans quoi, la searchBar ne fonctionne tout simplement pas !
Initialiser les données :
//ViewController.m
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
NSArray *group1 = [[NSArray alloc] initWithObjects:@"Napoli", @"Juventus", @"Inter", @"Milan", @"Lazio", nil];
NSArray *group2 = [[NSArray alloc] initWithObjects:@"Real Madrid", @"Barcelona", @"Villareal", @"Valencia", @"Deportivo", nil];
NSArray *group3 = [[NSArray alloc] initWithObjects:@"Manchester City", @"Manchester United", @"Chelsea", @"Arsenal", @"Liverpool", nil];
originalData = [[NSArray alloc] initWithObjects:group1, group2, group3, nil];
searchData = [[NSMutableArray alloc] init];
}
return self;
}
Maintenant nous devons initialiser nos deux objets, j'ai commenté le code pour expliquer ce que je fais :
//ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
/*the search bar widht must be > 1, the height must be at least 44
(the real size of the search bar)*/
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
/*contents controller is the UITableViewController, this let you to reuse
the same TableViewController Delegate method used for the main table.*/
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
//set the delegate = self. Previously declared in ViewController.h
self.tableView.tableHeaderView = searchBar; //this line add the searchBar
//on the top of tableView.
}
J'ai décidé de sauter la partie concernant l'initialisation de la cellule tableView, vous pouvez la trouver dans le code source téléchargeable :)
Lorsque le tableView est prêt, il est temps d'implémenter le UISearchDisplayControllerDelegate !
Le délégué dispose de nombreuses méthodes pour contrôler tous les aspects de la recherche, mais la plus importante est la suivante
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
Cette méthode est appelée chaque fois que vous insérez un nouveau caractère dans la barre de recherche. Elle prend la searchString, effectue la recherche dans les éléments du tableau et renvoie YES.
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[searchData removeAllObjects];
/*before starting the search is necessary to remove all elements from the
array that will contain found items */
NSArray *group;
/* in this loop I search through every element (group) (see the code on top) in
the "originalData" array, if the string match, the element will be added in a
new array called newGroup. Then, if newGroup has 1 or more elements, it will be
added in the "searchData" array. shortly, I recreated the structure of the
original array "originalData". */
for(group in originalData) //take the n group (eg. group1, group2, group3)
//in the original data
{
NSMutableArray *newGroup = [[NSMutableArray alloc] init];
NSString *element;
for(element in group) //take the n element in the group
{ //(eg. @"Napoli, @"Milan" etc.)
NSRange range = [element rangeOfString:searchString
options:NSCaseInsensitiveSearch];
if (range.length > 0) { //if the substring match
[newGroup addObject:element]; //add the element to group
}
}
if ([newGroup count] > 0) {
[searchData addObject:newGroup];
}
[newGroup release];
}
return YES;
}
C'est tout ! Cette méthode va effectuer une recherche en texte intégral dans tous les éléments. Lorsque la recherche est terminée, le tableView se recharge. Voir le code source pour voir d'autres détails.
Télécharger le fichier source (Lien mis à jour ! (04.01.2016) )