Ron*_*tin 46
这在Swift和Obj-C中完全相同:
首先,声明您的视图控制器符合 UIWebViewDelegate
class MyViewController: UIWebViewDelegate
Run Code Online (Sandbox Code Playgroud)
然后webViewShouldStartLoadingWithRequest:navigationType:
在View Controller中实现:
// Swift 1 & 2
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .LinkClicked:
// Open links in Safari
UIApplication.sharedApplication().openURL(request.URL)
return false
default:
// Handle other navigation types...
return true
}
}
// Swift 3
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
switch navigationType {
case .linkClicked:
// Open links in Safari
guard let url = request.url else { return true }
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
// openURL(_:) is deprecated in iOS 10+.
UIApplication.shared.openURL(url)
}
return false
default:
// Handle other navigation types...
return true
}
}
Run Code Online (Sandbox Code Playgroud)
最后,设置你UIWebView
的代表,例如,viewDidLoad
在你的故事板中或在你的故事板中:
webView.delegate = self
Run Code Online (Sandbox Code Playgroud)
小智 7
针对swift 3进行了更新
func webView(_: UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.linkClicked {
UIApplication.shared.open(shouldStartLoadWith.url!, options: [:], completionHandler: nil)
return false
}
return true
}
Run Code Online (Sandbox Code Playgroud)
小智 7
根据苹果文档中的建议
UIWebView 在 iOS 12 之后也被弃用
这是使用 Swift 5.3 和 WKWebiew 的解决方案
首先用 WKWebview 替换你的 UIWebview
然后符合WKNavigationDelegate并实现方法
这是代码
extension WebViewControllerImpl: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard case .linkActivated = navigationAction.navigationType,
let url = navigationAction.request.url
else {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
UIApplication.shared.openURL(url)
}
}
Run Code Online (Sandbox Code Playgroud)
然后为您的 wkWebView 设置“navigationDelegate”
wkWebView.navigationDelegate = self
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16364 次 |
最近记录: |