I want to show / hide UISearchBar programmatically but I am not having the desire results.
What I am trying to do is hide search bar when scrolling down and show it when scrolling up:
I set my UISearchBar like this:
var mySearchcontroller = UISearchController(searchResultsController: nil)
mySearchcontroller.obscuresBackgroundDuringPresentation = false
mySearchcontroller.searchBar.placeholder = "search"
mySearchcontroller.searchBar.delegate = self
definesPresentationContext = true
self.navigationItem.searchController = mySearchcontroller
self.navigationItem.hidesBackButton = true
self.navigationItem.hidesSearchBarWhenScrolling = false
And the result is
I implement the scrollViewDidScroll to make the search bar show or hide when scrolling:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if(scrollView.panGestureRecognizer.translation(in: scrollView.superview).y > 0)
{
navigationItem.hidesSearchBarWhenScrolling = false
}
else
{
navigationItem.hidesSearchBarWhenScrolling = true
}
}
And the result is:
As you realise that the GRP label or a segmented control is been masked by the search bar and I am not having the same effect where the search bar push down all controls (figure 1).
How can I solve this?
You achieve this functionality by following steps:
Give proper Auto-layout to your views.
Set IBOutlet for the Height of your headerview/searchview like:
@IBOutlet weak var constrainHeightHeader: NSLayoutConstraint!
Write the scrollview delegate methods like:
//MARK: - Scrollview delegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
//
self.contentOffSet = self.cwProducts.contentOffset.y
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//
let scrollPos = self.cwProducts.contentOffset.y
if scrollPos == self.contentOffSet{
return
}
if(scrollPos > self.contentOffSet ){
//Fully hide your toolbar
self.constrainHeightHeader.constant = 0
UIView.animate(withDuration: 0.2, animations: {
self.view.layoutIfNeeded()
}, completion: { (status) in
self.headerVW.isHidden = true
})
} else {
if(self.isFromBanner) {
self.constrainHeightHeader.constant = 0
}else{
self.constrainHeightHeader.constant = 50
}
UIView.animate(withDuration: 0.2, animations: {
self.view.layoutIfNeeded()
}, completion: { (status) in
self.headerVW.isHidden = false
})
}
}
I hope you are getting my point and by minor changes in the above code you will get solution.
It's working in my project 100% tested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With