Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show UISearchController when tableView swipe down

Tags:

search

ios

swift

I implemented the search bar in my test application via UISearchController. when I start my app, I see the search bar under the navigation controller. but how i can hide it when app is starts and show it only when I pull a table view down? and hide again when pull up a table view? I can't find any solution in google or youtube, please help.

EDIT: this is how I implement the UISearchController in viewDidLoad

//set the searchController
searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.sizeToFit()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search your restaurant"
tableView.tableHeaderView = searchController.searchBar
definesPresentationContext = true

tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
like image 618
Jack Daniel Avatar asked Oct 03 '15 13:10

Jack Daniel


2 Answers

Place the following segment in your viewDidLoad, so whats happening is your asking the UITableView to scroll and hide the SearchBar at the beginning :

tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)

And don't forget to set the TableViewHeader to your searchController :

tableView.tableHeaderView = searchController.searchBar

Update:

Because you have an empty tableview then replace the following :

tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)

With :

self.tableView.contentOffset = CGPointMake(0.0, 44.0)

Good luck !

like image 66
AaoIi Avatar answered Oct 08 '22 18:10

AaoIi


Swift 3:

Just after viewController appeared, you can scroll tableview to section 0, row 0 without animation.

In such a way tableHeaderView with the search bar would not be visible since it is located above section 0.

You simply scroll down the usual way to make it visible.

override func viewDidAppear(_ animated: Bool) {

    self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: UITableViewScrollPosition.top, animated: false)

}
like image 21
Rodion Avatar answered Oct 08 '22 18:10

Rodion