Swift: UISearchBar: Get text when search button clicked

Eudoxus picture Eudoxus · Jul 17, 2014 · Viewed 36.3k times · Source

I'm playing around with Swift to learn it and right now I'm having trouble getting the text from a UISearchBar

Right now my code looks like this:

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet var myWebView : UIWebView
    @IBOutlet var adressbar: UISearchBar

    override func viewDidLoad() {
        super.viewDidLoad()

        adressbar.showsScopeBar = true

        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: adressbar.text)
        var request = NSURLRequest(URL: url)

        myWebView.scalesPageToFit = true
        myWebView.loadRequest(request)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Answer

Alex Zielenski picture Alex Zielenski · Jul 17, 2014

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

import UIKit

class 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()
    }
}