Assuming you have the table view you are looking for, add the search bar and search controller to the table view in the storyboard. This will connect all the data sources / delegates you need.
Then in your table view you can use:
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool { doStuffWithSearchText(searchBar.text, scope: 0) }
which will be called every time the text in the search bar changes. Usually update the data displayed every time they change the text, but if you need to do this only when they click on the search button, use this function instead:
func searchBarSearchButtonClicked(searchBar: UISearchBar) { doStuffWithSearchText(searchBar.text, scope: 0) }
And you can get the text from the search results controller:
controller.searchBar.text
Or from the search bar:
searchBar.text
If you are not using a tableview controller:
- Add search bar
- Connect the view controller as a delegate to the search bar
- Then use the searchBarSearchButtonClicked: function to access when they click the Search button or searchBar (searchBar: UISearchBar, textDidChange searchText: String) to process w
I wrote a tutorial on this with a table view controller that has all the details: Adding a search bar to a table view in Swift
Christina
source share