How to filter UICollectionView and keep keyboard u

2019-03-17 19:36发布

I've added a UISearchBar to a UICollectionView and in the delegate searchBar:textDidChange: filter my model and call [collectionView reloadData]. reloadData (as well as reloadSection, etc) wants to take away firstResponder from the searchbar's textfield, thus dismissing the keyboard.

I am trying to build a "live updating" filter and so it's annoying to have the keyboard go away after each character typed.

Any ideas?

9条回答
Lonely孤独者°
2楼-- · 2019-03-17 19:57

I've just created a small test application. The following code does not hide the keyboard on entering characters in the searchbar. That said, [UITableView reloadData] does not resign the responder.

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return arc4random() % 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    return cell;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self.collectionView reloadData];
}

Are you sure, you're not resigning it somewhere?

查看更多
Evening l夕情丶
3楼-- · 2019-03-17 20:05

In searchBar delegate function , I use performBatchUpdates, first,reload collectionView then call [self.searchBar becomeFirstResponder] to display keyboard

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self setEditing:NO animated:YES];
    [searchBar setShowsCancelButton:YES animated:YES];

        [self.collectionView performBatchUpdates:^{
            [self.collectionView reloadData];
        } completion:^(BOOL finished) {
            [self.searchBar becomeFirstResponder];
        }];
}
查看更多
疯言疯语
4楼-- · 2019-03-17 20:05

I think you are calling the -resignFirstResponder method in the searchbar delegate which cause every time you enter the value it gets dismissed

You are in the right path about the datasource methods and reload data.Use an array to store all values another array for loading the collectionview and on every letter entered on the search bar filter and load the datasource array and then reload

Well i think it is better to keep the keyboard .That is the right UI style after you are done entering the text to search you can dismiss it manually.I think it is the better option for a live updating filter.

If you are using a button to search then you can include the keyboard hide option there.but the live update cannot be implemented when using such an option

查看更多
登录 后发表回答