搜索栏&网络视图

时间:2017-01-21 10:04:19

标签: ios swift

我正在尝试构建一个简单的Web浏览器。网络浏览器本身运行良好,但当我尝试搜索搜索栏中的网址时,我无法通过键盘返回打开网站。我该如何解决这个问题?

@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var webView: UIWebView!

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    let text = searchBar.text
    let urlSB = NSURL(string: text!)
    let reqSB = NSURLRequest(url:urlSB! as URL)
    self.webView!.loadRequest(reqSB as URLRequest)
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let url = NSURL(string: "https://www.google.com")
    let req = NSURLRequest(url:url! as URL)
    self.webView!.loadRequest(req as URLRequest)

}

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

2 个答案:

答案 0 :(得分:0)

您需要为UISearchBar实现delegate方法并从那里处理所有内容。另外,不要忘记将委托设置为viewcontroller。

答案 1 :(得分:0)

我为你写了一个演示:

结果:

第1步:

enter image description here

第2步:输入您要访问的网址。

enter image description here

步骤3:结果,webView加载您在searchBar中输入的网址:

enter image description here

代码如下:

import UIKit

class ViewController: UIViewController, UISearchBarDelegate {

@IBOutlet weak var searchBar: UISearchBar!

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "https://www.baidu.com")
    let req = NSURLRequest(url:url! as URL)
    self.webView!.loadRequest(req as URLRequest)

    searchBar.delegate = self

}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchBar.resignFirstResponder()
    let text = searchBar.text
    let urlSB = NSURL(string: text!)
    let reqSB = NSURLRequest(url:urlSB! as URL)
    self.webView!.loadRequest(reqSB as URLRequest)
}

// MARK: - searchbar delegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

    let urlStr =  "https://" + searchBar.text!

    let url = NSURL(string: urlStr)
    let req = NSURLRequest(url:url! as URL)
    self.webView!.loadRequest(req as URLRequest)

}

如果你的webView没有加载网址,请报告:

  

App Transport Security已阻止明文HTTP(http://)资源加载,因为它不安全。可以通过应用程序的Info.plist文件配置临时例外。

您可以转到info.plist打开如下的ATS,或搜索SO以查找详细信息方法:

enter image description here