如何向WKWebView添加导航栏?

时间:2015-02-18 22:02:30

标签: swift navigationbar wkwebview

我正在尝试使用WKWebView实现嵌入式webView。我有初始配置,并使用以下代码将网页加载到我的故事板中。

import UIKit
import WebKit

class WebViewViewController: UIViewController {
    @IBOutlet var containerView: UIView!
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        self.webView = WKWebView()
        self.view = self.webView!
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        var url = NSURL(string:"http://www.google.com/")
        var req = NSURLRequest(URL:url!)
        self.webView!.loadRequest(req)
    }

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


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

有了这个,我可以在我的应用程序中看到网页内容,但是没有导航栏,我需要允许用户输入所需的网址。如何像任何其他网络浏览器一样添加导航栏?

3 个答案:

答案 0 :(得分:9)

根据Devran Cosmo建议的网站link,这是我的最终视图控制器代码。

import UIKit
import WebKit

class WebViewViewController: UIViewController, UITextFieldDelegate, WKNavigationDelegate {

    var webView: WKWebView
    @IBOutlet weak var barView: UIView!
    @IBOutlet weak var urlField: UITextField!

    // Web Browser navigator
    @IBOutlet weak var backButton: UIBarButtonItem!
    @IBOutlet weak var forwardButton: UIBarButtonItem!
    @IBOutlet weak var reloadButton: UIBarButtonItem!
    @IBOutlet weak var progressView: UIProgressView!

    @IBAction func back(sender: UIBarButtonItem) {
        if (self.webView.canGoBack) {
            self.webView.goBack()
        }
    }

    @IBAction func forward(sender: UIBarButtonItem) {
        if (self.webView.canGoForward) {
            self.webView.goForward()
        }
    }

    required init(coder aDecoder: NSCoder) {
        self.webView = WKWebView(frame: CGRectZero)
        super.init(coder: aDecoder)
        self.webView.navigationDelegate = self
      }

    override func viewWillTransitionToSize(size: CGSize,  withTransitionCoordinator coordinator:     UIViewControllerTransitionCoordinator) {
        barView.frame = CGRect(x:0, y: 0, width: size.width, height: 30)
    }

    // Load user requested url
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        urlField.resignFirstResponder()
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlField.text)!))
        var list : WKBackForwardList = self.webView.backForwardList

        println("BACK LIST")
        println(list.backList)

        return false
    }

    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context:   UnsafeMutablePointer<()>) {
        if (keyPath == "loading") {
            backButton.enabled = webView.canGoBack
            forwardButton.enabled = webView.canGoForward
        }

        if (keyPath == "estimatedProgress") {
            progressView.hidden = webView.estimatedProgress == 1
            progressView.setProgress(Float(webView.estimatedProgress),  animated: true)
        }
    }

    func webView(webView: WKWebView!, didFinishNavigation navigation: WKNavigation!) {
        progressView.setProgress(0.0, animated: false)
    }

    func webView(webView: WKWebView!, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError!) {
        let alert = UIAlertController(title: "Error", message:  error.localizedDescription, preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .Default,  handler: nil))
        presentViewController(alert, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        barView.frame = CGRect(x:0, y: 0, width: view.frame.width, height: 30)

        // Do any additional setup after loading the view.
        view.insertSubview(webView, belowSubview: progressView)

        webView.setTranslatesAutoresizingMaskIntoConstraints(false)
        let height = NSLayoutConstraint(item: webView, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 1, constant: -44)
        let width = NSLayoutConstraint(item: webView, attribute:    .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 1,    constant: 0)
        view.addConstraints([height, width])

        // Disable navigation buttons on first loads
        backButton.enabled = false
        forwardButton.enabled = false

        webView.addObserver(self, forKeyPath: "loading", options: .New, context: nil)
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)

        let url = NSURL(string:"http://www.appcoda.com")
        let request = NSURLRequest(URL:url!)
        webView.loadRequest(request)
    }
}

答案 1 :(得分:4)

您必须将WebViewViewController包裹在UINavigationController内。并在navigationBar中添加所需的元素(后退按钮,刷新,位置文本字段)。

看起来像这样:

UINavigationController(rootViewController: WebViewViewController())

示例(将此代码放入AppDelegate中):

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = UINavigationController(rootViewController: WebViewViewController())
self.window?.makeKeyAndVisible()

还有关于如何在AppCoda上使用Webkit创建iOS浏览器的教程。

教程: 的 http://www.appcoda.com/webkit-framework-intro/

在该页面上,请参阅JFM的评论 - 该教程的作者犯了一些错误:)

答案 2 :(得分:0)

override func viewDidLoad() {
    super.viewDidLoad()
    let screenSize: CGRect = UIScreen.main.bounds
    let myView = UIView(frame: CGRect(x: 0, y: 72, width: screenSize.width, height: screenSize.height-72))
    self.view.addSubview(myView)
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    let configuration  = WKWebViewConfiguration()
    configuration.preferences = preferences
    webview = WKWebView(frame : myView.frame , configuration : configuration)
    webview.navigationDelegate = self
    view.addSubview(webview)
    webview.load(URLRequest(url : URL (string: url!)!))
    webview.allowsBackForwardNavigationGestures = true
}

我设计了72个px导航栏和WKWebView设置点(x:0,y:72),WkWebView框架是myView界限