我在我的第一个ViewController中有UIWebView,我想如果用户点击UIWebView 1中的任何链接应该打开新的ViewController(例如InfoViewController)并将URL传递给InfoViewController内的新UIWebView。
编辑:
我的代码:
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
}
答案 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)