Get text in the search bar

I want to use the search bar in my application. But I could not find any textbook for this.

My question is simple: how can I get text in the search bar when the user enters a button?

I need something like this in my controller:

override func userPressedToEnter(text: String) { println("User entered: \(text)") } 

How to do it fast?

+12
ios swift uisearchbar
source share
3 answers

Assuming you have a simple search bar in your storyboard, make sure it is plugged in as an outlet. Then use this as an example. Use the UISearchBarDelegate link to learn more about the delegation methods available to you.

 import UIKit class ViewController: UIViewController, UISearchBarDelegate { @IBOutlet var searchBar:UISearchBar! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. searchBar.delegate = self } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { print("searchText \(searchText)") } func searchBarSearchButtonClicked(searchBar: UISearchBar) { print("searchText \(searchBar.text)") } } 
+21
source share

I would look at the UISearchBarDelegate protocol: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UISearchBarDelegate_Protocol/index.html

Make your compliance controller class compliant with this protocol and you will have everything you need to interact with your search bar. Alternatively, you can get the text box in the search bar, but Apple provides you with a cleaner, more convenient, event-driven path through this protocol.

+1
source share

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

0
source share

All Articles