xeravim xeravim - 1 year ago 80
iOS Question

SearchDisplayController weird behaviour on UITableView HeaderView

I have been wondering how to implement the best practice for this kind of situation.

I have an UITableViewController, and want to add the searchBar programmatically, So I did this on my viewForHeaderInSection

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 44)];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 44)];
searchBar.placeholder = @"Search";
searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
searchDisplayController.delegate = self;
searchDisplayController.searchResultsDataSource = self;
searchDisplayController.searchResultsDelegate = self; //This one keep messing with the layout
[view setBackgroundColor:[UIColor blackColor]];
[view addSubview:searchBar];
return view;

The commented line causing my searchBar weird position and behaviour when editing as you can see on the image below.

Normal position

When firstResponder

first responder made the status bar overlap, though I have add on my viewDidLoad

self.edgesForExtendedLayout = UIRectEdgeNone;

And when editing it causing this : Doubled Search Bar
When Editing

If i remove the searchDisplayController.searchResultsDelegate = self; all the view looks perfect, but I need this delegate to fire the didSelectedRow on the searchResultTableView.. How can this possible? what is the best approach for this kind of situation. Thank you!


As I have searching here and there, and with the help of the answer given, I can conclude that If you want A fix SearchBar on UITableView, just create the tableview on UIViewController, put the searchBar, put some constraint and then voila!

Answer Source

Don't create your searchController in viewForHeaderInSection, instead create a searchController variable for your viewController like so:

let searchController = UISearchController(searchResultsController: nil)

Then configure it using this function and call this function in viewDidLoad:

func configureSearchController() {
    searchController.searchBar.delegate = self
    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    searchController.searchBar.barTintColor = UIColor.whiteColor()
    searchController.searchBar.tintColor = UIColor.blackColor()
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar


Here is a great link for how to accomplish this in objective-c: How to implement UISearchController with objective c