Domanda

Sto usando questo esempio del codice di esempio di Apple:

http://developer.apple.com/iPhone/library/samplecode/TableSearch/index.html

In questo esempio UITableView ottiene un elenco di contenuti all'avvio.Facendo clic sulla UISearchBar e digitando, l'elenco dei contenuti verrà filtrato, controllando anche l'ambito della ScopeBar.

Devo ricostruire questo tipo di "ricerca istantanea" in una "ricerca normale":All'inizio non ho dati per TableView.L'utente deve fare clic sulla barra di ricerca, digitare qualcosa, premere il pulsante "Cerca" e una richiesta di ricerca verrà inviata a un server web.La risposta del server web verrà inserita in TableView e l'utente potrà cambiare ambito per filtrare il set di risultati.La modifica del valore di SearchBar non filtra l'elenco dei risultati.Solo premendo il tasto "Cerca" si avvia una richiesta di ricerca.

Ho preso il codice di esempio e l'ho ricostruito (codice sorgente in fondo).Ma ho due problemi a riguardo.

  1. Alla chiamata iniziale di SearchViewController (con TabBar, SearchBar, ScopeBar, TableView), tutto va bene.C'è un TableView vuoto.Ma, facendo clic sulla barra di ricerca e digitando un solo carattere, viene visualizzato il messaggio "nessun risultato".Come potrei evitarlo?Questo messaggio dovrebbe apparire solo se un utente preme "Cerca" e non ci sono corrispondenze.
  2. Il mio secondo problema:Digitando "ciao" e premendo "Cerca" TableView non elenca i risultati.Se faccio clic su "Interrompi" o su un ambito diverso, verranno elencati i risultati.Quindi deve esserci qualcosa come una "ricarica" ​​mancante?!

Spero che qualcuno possa aiutarmi.Grazie mille in anticipo e saluti.

Il mio codice sorgente:

@implementation SearchViewController

@synthesize listContent, filteredListContent, savedSearchTerm, savedScopeButtonIndex, searchWasActive;

- (void)viewDidLoad {
    // restore search settings if they were saved in didReceiveMemoryWarning.
    if (self.savedSearchTerm) {
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:savedSearchTerm];
        self.savedSearchTerm = nil;
    }
}

- (void)viewDidUnload {
    // Save the state of the search UI so that it can be restored if the view is re-created.
    self.searchWasActive = [self.searchDisplayController isActive];
    self.savedSearchTerm = [self.searchDisplayController.searchBar text];
    self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
    self.filteredListContent = nil;
}

- (void)dealloc {
    [listContent release];
    [filteredListContent release];
    [super dealloc];
}

- (void)setData {
    self.listContent = [NSMutableArray arrayWithCapacity:3];
    [self.listContent addObject:[SearchObjects itemWithType:@"AAA" name:@"Test1"]];
    [self.listContent addObject:[SearchObjects itemWithType:@"BBB" name:@"Test2"]];
    [self.listContent addObject:[SearchObjects itemWithType:@"BBB" name:@"Test3"]];

    // create a filtered list
    self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.listContent count]];
    [self.tableView reloadData];
    self.tableView.scrollEnabled = YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //If the requesting table view is the search display controller's table view, return the count of the filtered list, otherwise return the count of the main list.
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [self.filteredListContent count];
    } else {
        return [self.listContent count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellID = @"cellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    /* If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list. */
    SearchObjects *searchObject = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        searchObject = [self.filteredListContent objectAtIndex:indexPath.row];
    } else {
        searchObject = [self.listContent objectAtIndex:indexPath.row];
    }
    cell.textLabel.text = searchObject.name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // HERE IS THE SOURCE CODE FOR PUSHING TO THE NEXT VIEW
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    // DO SOME CALCULATIONS… AND THE setData METHOD IS CALLED
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    /* Update the filtered array based on the search text and scope. */
    [self.filteredListContent removeAllObjects]; // First clear the filtered array.

    /* Search the main list for whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array. */
    for (SearchObjects *searchObject in listContent) {
        if ([scope isEqualToString:@"All"] || [searchObject.type isEqualToString:scope]) {
        NSComparisonResult result = [searchObject.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
            if (result == NSOrderedSame) {
                [self.filteredListContent addObject:searchObject];
            }
        }
    }
}

- (void)filterContentForScope:(NSString*)scope {
    /* Update the filtered array based on the search text and scope. */
    [self.filteredListContent removeAllObjects]; // First clear the filtered array.

    /* Search the main list for whose type matches the scope (if selected); add items that match to the filtered array. */
    for (SearchObjects *searchObject in listContent) {
        if ([scope isEqualToString:@"All"] || [searchObject.type isEqualToString:scope]) {
            [self.filteredListContent addObject:searchObject];
        }
    }
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    [self filterContentForScope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];    
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
    [self filterContentForScope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}
@end
È stato utile?

Soluzione 2

Il problema è risolto, vedi nei commenti.

Altri suggerimenti

Per il tuo primo problema dovresti impostare un delegato per la barra di ricerca e quindi implementarlo – searchBarSearchButtonClicked: e inserisci lì il codice di ricerca.Potrebbe anche essere necessario implementarne altri come – searchBarTextDidEndEditing: O – searchBar:textDidChange: e assicurati che non eseguano la ricerca.

Per la tua seconda domanda, potresti semplicemente ricaricare tableView utilizzando nuovamente il delegato da – searchBarSearchButtonClicked: per assicurarti che avvenga dopo aver già effettuato la ricerca.Puoi usare [tableView reloadData] per realizzare questo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top