you know thereβs a focus in the search bar.
- (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]; } }
When setting up a cell, ask the same question
- (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; }
Set filter options
-(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]; }
I hope to serve you, my English is very limited.
source share