Search code examples
uisearchbarcollectionviewswift4.2reloaddatabecomefirstresponder

Prevent Search bar from resigning being first responder SWIFT 4.2


I have a search bar in my collection view's header and I want to be able to filter the contents as user types. The problem is, every time i reload the collection view in textDidChange event of search bar, collection view becomes first responder and search bar resigns being, thus hiding keyboard.

I have checked all the answers in;

UICollectionView reloadData resigns first responder in section header

How to filter UICollectionView and keep keyboard up?

And any other posts that could be related but had no luck finding an answer. I'de be very happy if you guys can help.

Thanks in advance


Solution

  • 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?