问题
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