Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 263
Arthur Avatar asked Jun 24 '15 17:06

Arthur


2 Answers

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
                })
like image 139
Sergey Burd Avatar answered Oct 20 '22 00:10

Sergey Burd


In Xcode 7.3 in the ViewController.swift file it worked properly for me

CategoryTableView.tableHeaderView = searchController.searchBar // show

CategoryTableView.tableHeaderView = nil // hide
searchController.active = false
like image 32
Zvi Avatar answered Oct 19 '22 22:10

Zvi