Igy
Igy

Reputation: 129

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

Upvotes: 1

Views: 2727

Answers (2)

Anton Kondrashov
Anton Kondrashov

Reputation: 227

Beautiful hide and show using top constraint of search bar in Swift:

var lastContentOffset:CGFloat = 0 

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let bottomOffset = scrollView.contentSize.height - scrollView.bounds.height

    guard scrollView.contentOffset.y < bottomOffset  else {
        return
    }

    guard scrollView.contentOffset.y > 0 else {
        searchBarTopConstraint.constant = 0
        return
    }

    let offsetDiff = scrollView.contentOffset.y - lastContentOffset

    let unsafeNewConstant = searchBarTopConstraint.constant + (offsetDiff > 0 ? -abs(offsetDiff) : abs(offsetDiff))
    let minConstant:CGFloat = -searchBar.frame.height
    let maxConstant:CGFloat = 0

    searchBarTopConstraint.constant = max(minConstant, min(maxConstant, unsafeNewConstant))

    lastContentOffset = scrollView.contentOffset.y
}

Upvotes: 3

Laurent Rivard
Laurent Rivard

Reputation: 519

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

Upvotes: 4

Related Questions