Reputation: 463
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];
searchBar.delegate=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.
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
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!
UPDATE
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!
Upvotes: 1
Views: 198
Reputation: 1891
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
}
Objective-C
Here is a great link for how to accomplish this in objective-c: How to implement UISearchController with objective c
Upvotes: 1