简体   繁体   中英

How do I connect the search bar with the uiwebview in Xcode 6 using Swift?

I'm kinda new to coding with Swift and I need help: how do I connect the search bar to my web view so that when I type a search it appears in Google?

My code so far:

import UIKit

class ViewController: UIViewController      {

@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let url = NSURL(string: "http://google.com")
    let request = NSURLRequest(URL: url)
    webView.loadRequest(request)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

Here is a very basic example. Type this into the textField: http://www.apple.com

    import UIKit
    import WebKit

    class ViewController: UIViewController, UITextFieldDelegate {

        @IBOutlet weak var webView: UIWebView!
        @IBOutlet weak var textField: UITextField!

        @IBAction func Go(sender: AnyObject) {
            var text = textField.text
            var url = NSURL(string: text)
            var req = NSURLRequest(URL:url!)
            self.webView!.loadRequest(req)    
        }

        override func viewDidLoad() {
            super.viewDidLoad()

            self.textField.delegate = self
        }
    }

在此输入图像描述

Updated example showing a UISearchBar

import UIKit
import WebKit

class ViewController: UIViewController, UISearchBarDelegate {
    @IBOutlet weak var searchBar: UISearchBar!

    @IBOutlet weak var webView: UIWebView!

    func searchBarSearchButtonClicked(searchBar: UISearchBar!) {

        searchBar.resignFirstResponder()
        var text = searchBar.text
        var url = NSURL(string: text)  //type "http://www.apple.com"
        var req = NSURLRequest(URL:url!)
        self.webView!.loadRequest(req)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.searchBar.delegate = self
    }
}

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM