Search code examples
swifttableviewsearchbar

Swift autohide/show searchbar on top of tableview


I have successfully implemented a search bar, now i want when swipe down the tableview to show search bar, to swipe again down, to hide search bar. What methods should i use?Thank you


Solution

  • A UITableView is a subclass of UIScrollView which has delegate methods (from UIScrollViewDelegate) that you can use to find out when a scroll has started and ended.

    You can use the scrollViewDidScroll(_:) method to be notified when the user started scrolling, and the scrollViewDidEndDecelerating(_:) to be notified when the scroll has ended.

    From your question, I assume that you already have a method to show/hide the search bar; you are just looking for "when" to call your showSearchBar or hideSearchBar method.

    You could have a Bool property that stores whether the searchBar is hidden of not, and call you methods accordingly.

    let searchBarIsHidden = true
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
       if searchBarIsHidden {
           showSearchBar() //your show search bar function
       } else {
           hideSearchBar() //your hide search bar function
       }
    }
    

    Now you should make sure you update the value of searchBarIsHidden at the end of your showSearchBar and hideSearchBar