web-dev-qa-db-fra.com

Comment implémenter UISearchController avec l'objectif c

J'ai une application existante, écrite en objectif-c, avec une vue de table.

J'essaie maintenant de revenir à cette application et d'ajouter une barre de recherche au tableau.

Le problème est que maintenant il y a le nouveau protocole UISearchController, il semble y avoir très peu d'informations en ligne sur la façon de l'implémenter dans objective-c - tous les tutoriels et exemples que je peux trouver sont tous pour Swift.

J'ai ajouté les délégués au fichier .h:

UISearchBarDelegate, UISearchResultsUpdating

Et j'ai le code suivant dans viewDidLoad, qui fonctionne et ajoute une barre de recherche:

// Search controller
searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
searchController.searchResultsUpdater = self;
searchController.dimsBackgroundDuringPresentation = NO;
searchController.searchBar.delegate = self;

// Add the search bar
self.tableView.tableHeaderView = searchController.searchBar;
self.definesPresentationContext = YES;
[searchController.searchBar sizeToFit];

Et c'est aussi loin que j'ai!

J'apprécierais tous les pointeurs, exemples de code ou tutoriels sur la façon d'implémenter le nouveau UISearchController dans une vue de table d'application objective-c existante.

15
Richard

Initialiser les choses suivantes selon les étapes mentionnées.

1) Déclaration de protocole en<UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating> dans la classe d'interface .h

2) Déclarez les propriétés suivantes

//Fetch result controller 
@property (nonatomic, strong) UISearchController *searchController;

//for the results to be shown with two table delegates
@property (nonatomic, strong) CLCustomerResultrowsItemsCellController *searchResultsController;

//this custom controller is only suppose to have number of rows and cell for row function of table datasource

) Pour la restauration de l'état

 @property BOOL searchControllerWasActive;
 @property BOOL searchControllerSearchFieldWasFirstResponder;

4) Initialisez le code à cette étape dans ViewDidload

_searchResultsController = [[CLChatContactsSearchResultController alloc] init];
_searchController = [[UISearchController alloc] initWithSearchResultsController:_searchResultsController];

self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.placeholder = nil; 
[self.searchController.searchBar sizeToFit];
self.contactsTableView.tableHeaderView = self.searchController.searchBar;


// we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
self.searchResultsController.tableView.delegate = self;
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = YES; // default is YES
self.searchController.searchBar.delegate = self; // so we can monitor text changes + others

// Search is now just presenting a view controller. As such, normal view controller
// presentation semantics apply. Namely that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
//
self.definesPresentationContext = YES;  // know where you want UISearchController to be displayed

5) Utilisez le bouton même pour lancer le contrôleur et coller ces fonctions pour une utilisation future, le cas échéant, voir les commentaires

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}


#pragma mark - UISearchControllerDelegate

// Called after the search controller's search bar has agreed to begin editing or when
// 'active' is set to YES.
// If you choose not to present the controller yourself or do not implement this method,
// a default presentation is performed on your behalf.
//
// Implement this method if the default presentation is not adequate for your purposes.
//
- (void)presentSearchController:(UISearchController *)searchController {

}

- (void)willPresentSearchController:(UISearchController *)searchController {
    // do something before the search controller is presented
}

- (void)didPresentSearchController:(UISearchController *)searchController {
    // do something after the search controller is presented
}

- (void)willDismissSearchController:(UISearchController *)searchController {
    // do something before the search controller is dismissed
}

- (void)didDismissSearchController:(UISearchController *)searchController {
    // do something after the search controller is dismissed
}

6) Lors de la recherche dans le texte, vous obtenez ce rappel

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    // update the filtered array based on the search text
    NSString *searchText = searchController.searchBar.text;

    id <NSFetchedResultsSectionInfo> sectionInfo = [_fetchedResultsController.sections objectAtIndex:0];

    if (searchText == nil) {

        // If empty the search results are the same as the original data
        self.searchResults = [sectionInfo.objects mutableCopy];

    } else {

        NSMutableArray *searchResults = [[NSMutableArray alloc] init];

        NSArray *allObjects = sectionInfo.objects;

        for (PhoneNumber *phoneMO in allObjects) {

            if ([phoneMO.number containsString:searchText] || [[phoneMO.closrr_id filteredId] containsString:searchText] || [[phoneMO.contact.fullname lowercaseString] containsString:[searchText lowercaseString]]) {
                [searchResults addObject:phoneMO];
            }
        }

        self.searchResults = searchResults;

    }

    // hand over the filtered results to our search results table
    CLCustomerResultrowsItemsCellController *tableController = (CLCustomerResultrowsItemsCellController *)self.searchController.searchResultsController;
    tableController.filteredContacts = self.searchResults;
    [tableController.tableView reloadData];
}

7) Vous devez déclarer la propriété filterContacts dans la classe Custom qui remplira les éléments recherchés.

8) C'est tout, dans la ligne de sélection de comparer la vue de table si c'est le contrôleur principal ou la vue de table de classe de contrôleur personnalisé et de faire l'opération pour l'élément sélectionné.

J'espère que cela vous sera utile.

22
Vicky Dhas