你知道搜索栏是否有焦点。
- (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];
}
}
配置单元时做同样的问题
- (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;
}
设置过滤器参数
-(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];
}
我希望能为您服务,我的英语很有限