17

I'm trying to keep the search bar in view as the table scrolls. At the moment I'm placing it as the header in a tableview, and it works as it should, but of course the search bar scrolls off screen as you go down the table. I thought I could do this simply modifying this code sample:

How do I use UISearchController in iOS 8 where the UISearchBar is in my navigation bar and has scope buttons?

searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
tableview.tableHeaderView = searchContoller.searchBar // How to put it elsewhere?
//Alternative that also works
navigationItem.titleView = searchController.searchBar

The idea was to take some other view and do

otherview = searchController.searchBar

For instance an outlet to a UISearchBar, or a blank UIView, or something like that.

But it doesn't show the searchBar if I do that. It seems to only work as the header view of a table or as a navigationItem.titleView.

Am I missing something?

Community
  • 1
  • 1
Carlos
  • 5,991
  • 6
  • 43
  • 82
  • 1
    If you have a blank UIView place above the tableview, let's say you have an outlet to that blank UIView called `searchContainer`, then you can add the search bar to that view by `searchContainer.addSubview(searchController.searchBar)` – Praveen Gowda I V Jun 12 '15 at 06:56
  • That's right! Add and answer and you'll score some more points. – Carlos Jun 12 '15 at 15:14

1 Answers1

30

If you have a blank UIView that is placed above the tableview.

let's assume you have an outlet to that blank UIView called searchContainer. Then you can add the search bar of the UISearchController to that view by adding the following line

searchContainer.addSubview(searchController.searchBar)
Praveen Gowda I V
  • 9,569
  • 4
  • 41
  • 49
  • 1
    it worked great for me to add the searchBar in the view controller, but the searchResultsController doesn't trigger each time I try to edit, just the first time. But if I use a barButtonItem to launch the searchBar, the searchResultsController and the actual search triggers every time. Am I missing something here? – gadget00 Apr 10 '16 at 03:34
  • Occasionally you should setup your `viewDidLoad` method with `definesPresentationContext = true` and `extendedLayoutIncludesOpaqueBars = true` to prevent some layout misbehavior. – Leandro Fournier May 29 '17 at 13:33
  • Is there a way to set the height and width of the searchController.searchBar before/after adding as subview? – coolcool1994 Oct 01 '17 at 03:57