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

不问归期 提交于 2019-12-31 05:12:16

问题


How would i go about programmatically adding a search bar into a uitableview header? Specifically i have a bar button item that when it's pressed i would like to animate in a search bar into the table view header and when the cancel button is pressed it will animate back out of the view and the header scales back to normal. Would this be possible? Thanks.


回答1:


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
}



回答2:


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


来源:https://stackoverflow.com/questions/42200140/how-to-programmatically-add-a-search-bar-to-a-uitableview-header

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