Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show / hide UISearchBar programmatically in Swift

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

enter image description here

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:

enter image description here

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?

like image 869
Wael Avatar asked Nov 07 '22 09:11

Wael


1 Answers

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.

like image 61
Mr.Javed Multani Avatar answered Nov 14 '22 21:11

Mr.Javed Multani