如何使用多个按钮创建segue到webView

时间:2016-03-28 08:28:23

标签: ios swift webview segue

我有两个viewcontroller。我正在尝试使用按钮在一个webview中加载多个URL。我的第一个viewcontroller包含按钮,第二个viewcontroller包含一个uiwebview。我通过控制+点击+拖动将两个按钮连接到webview。这是我的代码。它不起作用。问题是什么?

第一个vc:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var link1: UIButton!

    @IBOutlet var link2: UIButton!

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

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

    @IBAction func link1(sender: AnyObject) {
        self.performSegueWithIdentifier("link1", sender: sender)
    }

    @IBAction func link2(sender: AnyObject) {
        self.performSegueWithIdentifier("link2", sender: sender)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.

        let websiteController = segue.destinationViewController as webViewController
        if segue.identifier == "link1" {
            websiteController.urlWebsite = "www.google.com"
        } else if segue.identifier == "link2" {
            websiteController.urlWebsite = "http://www.stackoverflow.com"
        }

    }



}

第二个vc:

import UIKit

class webViewController: UIViewController {

    @IBOutlet var webView: UIWebView!

    var urlWebsite: String?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let myURLString = urlWebsite
        let myURL = NSURL(string: myURLString!)
        let myURLRequest = NSURLRequest(URL: myURL!)
        webView.loadRequest(myURLRequest)

    }

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

1 个答案:

答案 0 :(得分:0)

我认为,您的问题出在这行代码中:

if segue.identifier == "link1" {
    websiteController.urlWebsite = "www.google.com"
}

您需要在网址中添加前缀 http:// 。所以您的代码如下所示

if segue.identifier == "link1" {
    websiteController.urlWebsite = "http://www.google.com"
}