How to programmatically add a search bar to a UITableView header?

喜欢而已 提交于 2019-12-02 12:23:38

It's based on Swift 2 but It's not very diff to swift 3

Add search delegate to view controller:

UISearchResultsUpdating

Make a search:

let searchController = UISearchController(searchResultsController: nil)

Set this default values for searchController:

searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true

Add search to table:

table.tableHeaderView = searchController.searchBar

This delegate let you know start searching:

func updateSearchResultsForSearchController(searchController: UISearchController) {
    filterContentForSearchText(searchController.searchBar.text!)
}

Impliment your search function:

func filterContentForSearchText(searchText: String, scope: String = "All") {
    // do some stuff
}
Sourabh Kumbhar

Setup the Search Bar programatically

First add UISearchBarDelegate to your class

let searchBar = UISearchBar()
searchBar.frame = CGRect(x: 0, y: 0, width: 200, height: 70)
searchBar.delegate = self
searchBar.showsCancelButton = true
searchBar.searchBarStyle = UISearchBarStyle.default
searchBar.placeholder = " Search Here....."
searchBar.sizeToFit()

and add the search bar to UITableView header

tableView.tableHeaderView = searchBar
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!