2012-07-28 9 views
6

Estoy implementando un UISearchDisplayController y me gustaría rellenar el searchResultsTableView con el contenido del tableView (sin filtrar) justo en el momento de la carga, antes de ingresar el texto.¿Cómo mostrar searchResultsTableView cuando la barra de búsqueda está activada?

Esto funciona cuando comienzo a ingresar valores en searchBar.

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller { 
    self.isSearching = YES; 

    //tell the searchDisplayTableView to show here! 

    [controller.searchBar setShowsCancelButton:YES animated:YES]; 
} 

- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller { 
    self.isSearching = NO; 
    [controller.searchBar setShowsCancelButton:NO animated:YES]; 
} 

¿Alguien tiene alguna indicación en la dirección correcta?

No responda con "no hacer eso" o "Apple no diseñó el control de esa manera". o ...

+0

¿Has encontrado una solución? Tengo exactamente el mismo problema. – nonamelive

+0

¿Alguien ha resuelto cómo hacer esto todavía? – Chicken

Respuesta

0

el control de Apple funciona así. Lo resolví implementando un controlador independiente (llamarlo controlador de visualización de búsqueda) que es un delegado de la barra de búsqueda y aplica un predicado a la fuente de datos. De esta forma, la tabla se filtra 'en línea'.

0

Es necesario volver a cargar la vista de tabla utilizando el resultado filtrado en la búsqueda está haciendo: En este método sólo llame vista de tabla reloadData:

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller { 
    self.isSearching = YES; 
    [yourTableView reloadData]; 
    [controller.searchBar setShowsCancelButton:YES animated:YES]; 
} 

y modificar su método numberOfSectionsInTableView como:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    if(isSearching == YES) 
    { 
     yourDataArray = //filtered result; 
    } 
    else 
    { 
     yourDataAray = //unfiltered result; 
    } 
    return 1; 
} 

Espero que te ayude.

+0

Hola Midhun, gracias por tu comentario, pero no funciona del todo. Cuando activo la búsqueda, searchDisplayController atenúa tableView (aunque todavía vemos contenido pero no podemos controlarlo). Cuando se ingresa texto en searchBar, el searchDisplayTableView se carga con el contenido (filtrado o no, esto puedo controlar), quiero mostrar. – Ron

+0

@Ronny: cuando comienza a escribir, la vista de tabla se oscurece; después de escribir una sola letra, la vista de tabla pasa al estado anterior (no atenuada). Creo que es tu problema, ¿estoy en lo correcto? –

+0

@Ronny: ¿sigues teniendo el problema? –

0
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller 
{ 
    // Here is a table we want to show in UISearchDisplayController 
    XXRecentSearchDataSource *recentSearch = [XXRecentSearchDataSource recentSearchDataSource]; 
    recentSearch.delegate = self; 

    // Setup default table view 
    CGRect frame = CGRectMake(0.0f, 
         CGRectGetMaxY(controller.searchBar.frame), 
         CGRectGetWidth(self.view.bounds), 
         CGRectGetHeight(self.view.bounds) - CGRectGetHeight(controller.searchBar.bounds)); 

    // Setup temporary table and remember it for future use 
    [_tempRecentSearchTableView release]; 
    _tempRecentSearchTableView = [[UITableView alloc] initWithFrame:frame 
                   style:UITableViewStylePlain]; 
    _tempRecentSearchTableView.dataSource = recentSearch; 
    _tempRecentSearchTableView.delegate = recentSearch; 

    [self performSelector:@selector(removeOverlay) withObject:nil afterDelay:.0f]; 
} 

- (void)removeOverlay 
{ 
    [[self.view.subviews lastObject] removeFromSuperview]; 
    [self.view addSubview:_tempRecentSearchTableView]; 
} 

En algunos casos, debe recordar eliminar _tempRecentSearchTableView. Por ejemplo:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    // Remove temporary table view 
    [_tempRecentSearchTableView removeFromSuperview]; 
} 
0

sabe si la barra de búsqueda tiene enfoque.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if ([_searchBar isFirstResponder]) { 
       return [_filteredData count]; 
    } else { 

     id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
     return [sectionInfo numberOfObjects]; 

    } 
} 

Al configurar la célula hacen la misma pregunta

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *CellIdentifier = @"CustomCell"; 
    CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 
    if (cell == nil) { 
     cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    Entidad *e = nil; 

    if ([_searchBar isFirstResponder]) 
    { 
     e = [self.filteredData objectAtIndex:indexPath.row]; 

    } 
    else 
    { 
     e = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    } 

    cell.nameLabel.text = e.titulo; 
    cell.thumbnailImageView.image = [UIImage imageNamed:@"password-50.png"]; 
    cell.dateLabel.text = e.sitio; 

    return cell; 
} 

Establecer los parámetros del filtro

-(void)filter:(NSString*)text 
{ 

    _filteredData = [[NSMutableArray alloc] init]; 


    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 


    NSEntityDescription *entity = [NSEntityDescription 
            entityForName:@"Entidad" inManagedObjectContext:self.managedObjectContext]; 
    [fetchRequest setEntity:entity]; 


    NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] 
             initWithKey:@"titulo" ascending:YES]; 
    NSArray* sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 
    [fetchRequest setSortDescriptors:sortDescriptors]; 


    if(text.length > 0) 
    { 

     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(titulo CONTAINS[c] %@)", text]; 
     [fetchRequest setPredicate:predicate]; 
    } 

    NSError *error; 


    NSArray* loadedEntities = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
    _filteredData = [[NSMutableArray alloc] initWithArray:loadedEntities]; 

    NSLog(@"%@", _filteredData); 

    [self.tableView reloadData]; 
} 

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text 
{ 
    [self filter:text]; 
} 

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{ 

    [self filter:@""]; 

    [_searchBar resignFirstResponder]; 
    [_searchBar setText:@""]; 
    [_tableView reloadData]; 
} 

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar 
{ 

    [_searchBar setShowsCancelButton:YES animated:YES]; 
} 

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar 
{ 
    [_searchBar setShowsCancelButton:NO animated:YES]; 
} 

espero servirle, mi Inglés es muy limitado

Cuestiones relacionadas