2

I am trying to implement search to my app. I used to read and watch several tutorials, and all of them recommend to put Search Bar to Table Header:

self.tableView.tableHeaderView = self.searchController.searchBar

Search works pretty good, but there is a problem: when i scroll the table, searchbar goes out of the screen:

enter image description here

And this is not what i want. I'd like to perform a search like in iPhone Contacts.

Any thoughts?

May be there is an option to stop tableHeader from scrolling out (like section headers stay on the screen while you can see any cell from this section)

3 Answers3

4

If your parent controller has a UINavigationController, you can stick the search bar in the navigation bar, like so:

self.navigationItem.titleView = _searchController.searchBar;

Alternatively, you could create a blank UIView at the top of the screen and put the UITableView underneath it. Then you add the UISearchController's search bar as a subview of the blank view, as described in How do I set the UISearchController's searchBar to a view that isn't the tableHeaderView or navigationItem.titleview?.

Community
  • 1
  • 1
AndrewR
  • 10,759
  • 10
  • 45
  • 56
0

You can use -

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

method to add search bar on section header. If there is only one section then I think this will work for you.

sagar.musale
  • 585
  • 1
  • 7
  • 19
0

It can be done in swift in following ways:

First if you do not want that navigation bar will hide when you start writing in search bar then write this line:

    searchController.hidesNavigationBarDuringPresentation = false;

Then assign search bar to navigationItem title view:

    self.navigationItem.titleView = self.searchController.searchBar;
H S W
  • 6,310
  • 4
  • 25
  • 36