将URL控件从ViewController 1中的UIWebView 1传递到ViewController 2中的UIWebView 2

时间:2016-04-07 09:00:28

标签: ios objective-c xcode swift

我在我的第一个ViewController中有UIWebView,我想如果用户点击UIWebView 1中的任何链接应该打开新的ViewController(例如InfoViewController)并将URL传递给InfoViewController内的新UIWebView。

编辑:

My Storyboard

我的代码:

class ViewController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let url = NSURL (string: "https://google.com");
    let requestObj = NSURLRequest(URL: url!);
    webview.delegate = self;
    webview.loadRequest(requestObj);

}

func webview(WebViewNews: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {

    if (navigationType == UIWebViewNavigationType.LinkClicked) {
    //Push to new view controller here and pass new url:
    let url = request.URL
    let infoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("InfoViewController") as! InfoViewController
    infoViewController.passURL = url.absoluteString //Add passURL property in your InfoViewController

    self.navigationController!.pushViewController(infoViewController, animated: true)

    //prevent the current webview from loading the page
    return false
    }

    //webview will load first time normally/other requests will load
    return true
}

2 个答案:

答案 0 :(得分:1)

将webview委托设置为self:

webview.delegate = self

然后你可以添加这个委托方法。只要它尝试加载URL,它就会运行。您可以添加if检查以确保它是他们单击的链接并运行您的代码以更改屏幕并阻止当前webview通过返回false加载URL:

//Update: got method name wrong:
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {

    if (navigationType == UIWebViewNavigationType.LinkClicked {
         //Push to new view controller here and pass new url:
         let url = request.URL
         let infoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("InfoViewController") as InfoViewController
         infoViewController.passURL = url.absoluteString //Add passURL property in your InfoViewController

         self.navigationController!.pushViewController(infoViewController, animated: true)

         //prevent the current webview from loading the page
         return false
    }

    //webview will load first time normally/other requests will load
    return true
}

答案 1 :(得分:0)

  1. 您需要从第一个UIWebview中提取链接: iPhone - UIWebview - Get the URL of the link clicked
  2. 打开新的ViewController并传递字符串。
  3. 指示您的第二个UIWebview打开网址。