我如何设置我的UISearchBar连接到我的UIWebView能够与一个字,而不是使用URL迅速在

2019-11-03 09:29发布

如何设置我的UISearchBar连接到我的UIWebView能够与一个字,而不是一个网址在谷歌搜索。 例如搜索苹果,而不是http://www.apple.com

继承人到目前为止我的代码

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

    let url = NSURL(string: "http://google.com")
    let request = NSURLRequest(URL: url)
    webView.loadRequest(request)

    self.searchBar.delegate = self
     }
}

Answer 1:

您需要将字符串从您的UISearchBar追加到下面的字符串http://www.google.com/search?q=然后创建一个URL。 追加像这样的字符串

text = text.stringByReplacingOccurrencesOfString(" ", withString: "+");
var url = NSURL(string: "http://google.com/search?q=".stringByAppendingString(text));

因此,对于苹果的搜索会是什么样子http://www.google.com/search?q=apple



Answer 2:

这是我如何实现这一点使用斯威夫特3和输入一个TextField。 希望它可以帮助别人。

 func search(){
        var searchTerms = self.searchTextField.text!
        searchTerms = searchTerms.replacingOccurrences(of: " ", with: "+")

        let urlString = "http://www.google.com/search?q=\(searchTerms)"
        let url = URL(string: urlString)

        let request = URLRequest(url: url!)
        webView.loadRequest(request)
        self.searchTextField.endEditing(true)//dismiss keyboard
    }


文章来源: How do I Setup my UISearchBar connected to my UIWebView to be able to search on google with a word instead of a url using swift