Arthur Arthur - 3 months ago 116
iOS Question

How to show/hide UISearchBar by action in Swift?

I have a

UITableView
with a
UISearchBar
. I need to show/hide my
searchBar
, by user action (button pressing):

I tried to use this code:

if self.tableView.contentOffset.y == 0 {
self.tableView.contentOffset = CGPoint(x: 0.0, y: self.searchBar.frame.size.height)
}


from this question.
Actually I've tried all of those answers. All of them just scroll my
UITableView
, and each time I'm scrolling my
UITableView
-
searchBar
appears.
I tried to do something like this:

self.newsTableView.tableHeaderView = nil; //Hide


and

self.newsTableView.tableHeaderView = self.SearchBar; //Show


But
UITableView
doesn't want to return
searchBar
;

How can I resolve this problem?
I need to hide
searchBar
by action, not to scroll my
UITableView
(hide like
searchBar.hidden = true
) Actually,
searchBar.hidden = true
works, but there is a white space instead of
searchBar
.

Answer

Use UIView.animation for searchBar and tableView When you start scroll table Change position/alpha of search bar and height of tableView

UIView.animateWithDuration(1.0, animations: {
          searchBar.alpha = 0.0
          tableView.view.frame.height = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height)
                    }, completion: {
                        (value: Bool) in
                        //do nothing after animation
                })