iOS UIWebView 拦截点击事件(双击缩放)

时间:2021-02-27 19:28:01

在平时的开发中,要使用到webview,但类似微信的webview在数据没有加载完成的时候

双击屏幕,webview不会缩放,其实实现这个功能很简单

代码是用swift写的

 1 class YYSimpleWebViewController: UIViewController,UIWebViewDelegate,UIGestureRecognizerDelegate {
2
3 var urlS :NSURL?
4 var cusWebView :UIWebView!
5 var isLoaded = false
6 let cover = UIView()
7
8 init(WithUrl webUrl :NSURL?) {
9 super.init(nibName: nil, bundle: nil)
10 self.urlS = webUrl
11 cusWebView = UIWebView()
12 cusWebView.delegate = self
13 NSURLCache.sharedURLCache().removeAllCachedResponses()
14 NSURLCache.sharedURLCache().diskCapacity = 0
15 NSURLCache.sharedURLCache().memoryCapacity = 0
16
17 }
18
19 required init?(coder aDecoder: NSCoder) {
20 fatalError("init(coder:) has not been implemented")
21 }
22
23
24
25 override func viewDidLoad() {
26 super.viewDidLoad()
27 cusWebView.frame = self.view.bounds
28 self.view.addSubview(cusWebView)
29
30
31 cover.backgroundColor = UIColor.clearColor()
32 cover.frame = cusWebView.bounds;
33 cusWebView.scrollView.addSubview(cover)
34
35 print(cusWebView.gestureRecognizers)
36 let doubleTap = UITapGestureRecognizer(target: self, action: "tap")
37 doubleTap.numberOfTapsRequired = 2
38 doubleTap.delegate = self
39 cover.addGestureRecognizer(doubleTap)
40
41 if self.urlS != nil {
42
43 cusWebView.loadRequest(NSURLRequest(URL: self.urlS!))
44 }
45
46
47 }
48 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
49 return true
50 }
51
52 func webViewDidFinishLoad(webView: UIWebView) {
53
54 self.cover.removeFromSuperview()
55 self.title = webView.stringByEvaluatingJavaScriptFromString("document.title")
56 }
57
58 func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
59 self.cover.removeFromSuperview()
60 }
61 func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
62
63 return true
64 }
65
66
67 func tap() {
68
69 }

核心思想就是在在webview的上边加一个透明的view,加载完成后移除,在加载过程中,拦截双击事件