Reputation: 470
In my app I have a UITableViewController
, and I want to add a searchbar to it. The tableview has 3 sections which expand when clicked on one of them. I added this code to viewDidLoad
:
searchBar.showsScopeBar = true
searchBar.delegate = self
searchBar.frame = CGRectMake(0, 0, tableView.frame.size.width, 100)
self.view.addSubview(searchBar)
The problem is: the searchbar appears in the first section when you open it, and it should appear above the whole tableview, any suggestions? Any help is appreciated!
Upvotes: 0
Views: 140
Reputation: 191
You can find pretty helpful example in Programming iOS 9 by Matt Neuburg, inside chapter II: Table Views and Controller Views.
let src = SearchResultsController(data: self.sectionData)
let searcher = UISearchController(searchResultsController: src)
self.searcher = searcher
searcher.searchResultsUpdater = src
let b = searcher.searchBar
b.sizeToFit() // crucial, trust me on this one
b.autocapitalizationType = .None
self.tableView.tableHeaderView = b
self.tableView.reloadData()
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition:.Top, animated:false)
He also warns, that adding search bar as the table view's header view may have an odd effect: it causes the table view's background color to be covered by an gray color, visible above the search bar when the user scrolls down. The official workaround is to assign the table view a backgroundView with the desired color.
Upvotes: 1
Reputation: 1680
You can add searchBar
as a tableHeaderView
of the TableView
of your UITableViewController
.
Upvotes: 1