Uicollectionview Reloaddata Resigns First Responder/Dismisses Keyboard When Searchbar Is in Section Header

Prevent Search bar from resigning being first responder SWIFT 4.2

I could not find any proper solution for this issue so I've added my searchbar to my main view and synchronized its height value with my collection views didscroll event.

Here is the code snippet if anyone is interested.

    let offset = self.collectionView.contentOffset
let y = offset.y

if lastContentOffset > scrollView.contentOffset.y && lastContentOffset < scrollView.contentSize.height - scrollView.frame.height {
// move up
if self.cst_searchBarHeight.constant == 0 && y <= 0{
self.cst_searchBarHeight.constant = self.searchBarHeight
UIView.animate(withDuration: 0.4, delay: 0.0, options: [.curveEaseInOut], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}

} else if lastContentOffset < scrollView.contentOffset.y && scrollView.contentOffset.y > 0 {
// move down
if self.cst_searchBarHeight.constant != 0{
self.cst_searchBarHeight.constant = 0
UIView.animate(withDuration: 0.4, delay: 0.0, options: [.curveEaseInOut], animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
// update the new position acquired
lastContentOffset = scrollView.contentOffset.y
}

I've got the idea from the below answer which finds out the scroll direction of collection view
How can I detect the scroll direction from the UICollectionView?

How to reload only data section of UICollectionView?

I think the error only occurs when the search bar is a collection view's subview, and trying to call reloadSections: when the keyboard input is up.

This article gives an answer to a similar problem, but that didn't work for me.

So I used an alternative way with which I can invoke almost the same feature.

Instead of adding the header as a supplementary view, I made the header a subview of 'view'. (not collectionView)

And added some scroll delegate to mimic the table view's header.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat y = scrollView.contentOffset.y;
if (y < 44) {
[self.searchBar setFrame:CGRectMake(0, -y, 320, 44)];
[self.searchBar setHidden:NO];
} else if (y >= 44) {
[self.searchBar setHidden:YES];
}
}


Related Topics



Leave a reply



Submit