I want to use search bar in my app. But I couldn't find any tutorial for this.
My question is simple: How can I get search bar text when user preses to enter button ?
I need something like this in my view controller:
override func userPressedToEnter(text: String) {
println("User entered: \(text)")
}
How can I do this in swift ?
Now, let’s build a search bar by implementing the SearchBar.swift file. If you look at the standard search bar in iOS, it’s actually composed of a text field and a cancel button. First, we declared two variables: one is the binding of the search text and the other one is a variable for storing the state of the search field (editing or not).
If you look at the standard search bar in iOS, it’s actually composed of a text field and a cancel button. First, we declared two variables: one is the binding of the search text and the other one is a variable for storing the state of the search field (editing or not).
1.First thing is to conform to the UISearchbarDelegate. 2.Set the search bar delegate to self. If your outlet name for your UISearchBar is 'searchBar'... @IBOutlet weak var searchBar: UISearchBar!
Again, you can test the search bar in the preview by clicking the Play button. Now that the search bar is ready for use, let’s switch over to ContentView.swift and add the search bar to the list view. Right before the List view, insert the following code: This will add the search bar between the title and the list view.
Assuming you have a simple search bar in your storyboard, make sure you have it connected as an outlet. Then use this as an example. Use UISearchBarDelegate the reference to learn more about delegate 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)")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With