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