I'm trying to add a search bar to a view, but I've tried it a thousand ways and the searchbar delegate does not work.
class SearchTableViewController: UITableViewController, UISearchBarDelegate{
override func viewDidLoad() {
super.viewDidLoad()
let searchController = UISearchController(searchResultsController: nil)
searchController.dimsBackgroundDuringPresentation = true
searchController.obscuresBackgroundDuringPresentation = true
self.definesPresentationContext = true
searchController.searchBar.delegate = self
self.tableView.tableHeaderView = searchController.searchBar
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
I ran into the same problem.
The issue you are having is that UITableViewController has a big restriction: its main view must be a UITableView that takes up the entire screen space (except for a possible navigation bar at the top, and a toolbar or tab bar at the bottom).
If your screen consists of just a UITableView, then it makes sense to use it. However, since you are adding a search bar, you must use a UIViewController and add a UITableView to it. Then you can add the search bar as you like.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.