相当于
的等价物webView.delegate = self
是否在WKWebView中?我有
webView2.UIDelegate = self
但它不能按预期工作。
答案 0 :(得分:5)
您可以使用键值观察来监控WKWebView的canGoBack和canGoForward。
SWIFT 3
向WKWebView添加两个键值观察器。
let webView = WKWebView(frame: view.frame)
view.addSubview(webView)
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.canGoBack), options: .new, context: nil)
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.canGoForward), options: .new, context: nil)
现在,在视图控制器中实现observeValue(forKeyPath :)方法。
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.canGoBack) || keyPath == #keyPath(WKWebView.canGoForward) {
// Do Something...
}
}
例如,您可以将这样的内容添加到按钮的更改色调颜色。
backButton.imageView?.tintColor = webView.canGoBack ? UIColor.blue : UIColor.gray
forwardButton.imageView?.tintColor = webView.canGoBack ? UIColor.blue : UIColor.gray
我通过阅读这里的文章找到了这种方法。
答案 1 :(得分:0)
您确定代码的only
更改正在将UIWebView
更改为WKWebView
吗?我制作了一个示例项目,并且点按手势识别器适用于UIWebView
和WKWebView
。以下是相关代码:
class ViewController: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: view.frame)
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
let urlString = "https://www.google.com"
let url = NSURL(string: urlString)!
let urlRequest = NSURLRequest(URL: url)
webView.loadRequest(urlRequest)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(webViewTapped))
recognizer.delegate = self
webView.addGestureRecognizer(recognizer)
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func webViewTapped(recognizer: UITapGestureRecognizer) {
print("Tapped")
}
}