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
¿Has encontrado una solución? Tengo exactamente el mismo problema. – nonamelive
¿Alguien ha resuelto cómo hacer esto todavía? – Chicken