Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get searchbar text in swift

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 ?

like image 338
Okan Avatar asked May 05 '15 16:05

Okan


People also ask

How to build a search bar 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).

How does the standard iOS search bar work?

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).

How to add a search bar in uisearchbar?

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!

How do I add a search bar to a list view?

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.


1 Answers

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)")
    }

}
like image 89
Frankie Avatar answered Oct 15 '22 03:10

Frankie