Swift: UISearchBar: Get text when search button clicked Swift: UISearchBar: Get text when search button clicked ios ios

Swift: UISearchBar: Get text when search button clicked


In viewDidLoad you must set the delegate of the search bar to be receiving searchBarSearchButtonClicked from it:

import UIKitclass SecondViewController: UIViewController, UISearchBarDelegate{    @IBOutlet var myWebView : UIWebView    @IBOutlet var adressbar: UISearchBar    override func viewDidLoad()    {        super.viewDidLoad()        adressbar.showsScopeBar = true        adressbar.delegate = self        var url = NSURL(string: "http://google.com")        var request = NSURLRequest(URL: url)        myWebView.scalesPageToFit = true        myWebView.loadRequest(request)    }    func searchBarSearchButtonClicked( searchBar: UISearchBar!)    {        var url = NSURL(string: searchBar.text)        var request = NSURLRequest(URL: url)        myWebView.scalesPageToFit = true        myWebView.loadRequest(request)    }    override func didReceiveMemoryWarning()    {        super.didReceiveMemoryWarning()    }}


1.First thing is to conform to the UISearchbarDelegate.

2.Set the search bar delegate to self.

You can find more on this here Swift iOS tutorial : Implementing search using UISearchBar and UISearchBarDelegate


Simple (non-specific) answer for those arriving here via search:

If your outlet name for your UISearchBar is 'searchBar'...

@IBOutlet weak var searchBar: UISearchBar!

Then the text entered by the user in UISearchBar is called...

searchBar.text

Two common things Swift coders forget:1. Make sure to add UISearchBarDelegate class...

ViewController: UIViewController, UISearchBarDelegate
  1. Don't forget to identify your view class as the delegate...Inside viewDidLoad you could write...

    searchBar.delegate = self

If you forget #1 above you won't be able to auto-complete the methods you'll need to implement like...

func searchBarSearchButtonClicked(_ seachBar: UISearchBar) { your code }

... which is given to you by the delegate protocol.


matomo