Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

ios - UICollectionView reloadData resigns first responder/dismisses keyboard when searchBar is in section header

I have a UICollectionView that have section header. In the section header I have a UISearchBar. I want to filter the content in my collection view when I type in the search bar. I do this with the following method:

// The method to change the predicate of the FRC
- (void)filterContentForSearchText:(NSString*)searchText
{
    NSString *query = searchText;
    if (query && query.length) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@ or createdAt contains[cd] %@ or noteText contains[cd] %@ or keywords contains[cd] %@", query, query, query, query];
        [self.fetchedResultsController.fetchRequest setPredicate:predicate];
    } else {
        [self.fetchedResultsController.fetchRequest setPredicate:nil];
    }
    NSError *error = nil;
    if (![[self fetchedResultsController] performFetch:&error]) {
        // Handle error
        NSLog(@"Error");
    }
    [self.collectionView reloadData];
}

This method gets called every time the search bar text changes. The line [self.collectionView reloadData] hided the keyboard for every character. Is it possible to reload only the data in a UICollection view and not reload the Supplementary views like section headers headers?

The data in my collectionView comes from a NSFetchResultController.

I'm pretty happy with how my UI works so if there is a simple way to NOT reload the section header, then that would be great!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I finally figured this out after trying many different options. The solution is to make your header of its own section so you can reload the other sections independently without reloading the one your header is attached to.

So:

  • Section 0
    • Header
      • Search bar (or other text fields)
    • Rows
      • (None)
  • Section 1
    • Header
      • Create an empty UICollectionReusableView and override ...sizeForItemAtIndexPath:(NSIndexPath *)indexPath to return CGSizeZero
    • Rows
      • Your actual rows that would have originally gone with section 0

Then, we you need to reload your data:

[collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];

Your searchbar or text fields should retain their focus while the user is typing and you can update the results in the background.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...