14

Is it possible to put UISearchBar of UISearchController somewhere other than header view of UITableView?

In the apple's sample code for UISearchController, following is used.

[self.searchController.searchBar sizeToFit];
self.tableView.tableHeaderView = self.searchController.searchBar; 

Is it possible to position searchBar somewhere else? Say we want to implement a fixed UISearchBar like the one used in contacts app. I've tried this but the searchBar doesn't appear at all.

madhead
  • 31,729
  • 16
  • 153
  • 201
MTRL
  • 143
  • 1
  • 6

3 Answers3

19

You can place the UISearchBar of UISearchController in the navigation bar so that it remains fixed

self.searchController.hidesNavigationBarDuringPresentation = NO;
self.searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;

// Include the search bar within the navigation bar.
self.navigationItem.titleView = self.searchController.searchBar;

self.definesPresentationContext = YES;
Praveen Gowda I V
  • 9,569
  • 4
  • 41
  • 49
  • I was about to rip out the `SearchController` again for a manually managed `UISearchBar` before reading your answer, thanks for saving me a bunch of time! – JoniVR Jul 11 '20 at 15:50
9

Create One uiview and added searchController.searchbar inside this view. After that add this view in your viewController.view. above the table view.

then it will not scroll.

   var viewTemp = UIView(frame: CGRectMake(0.0, 64.0,320.0, 44))
   viewTemp.addSubview(self.searchController.searchBar)
   self.view.addSubview(viewTemp);
NASSER
  • 5,900
  • 7
  • 38
  • 57
anil
  • 121
  • 5
0

Instead of directly keeping UISearchBar on top of UITableView. Put the UISearchBar inside a view.enter image description here

Saurabh Padwekar
  • 3,888
  • 1
  • 31
  • 37