原文:http://blog.csdn.net/favormm/article/details/6614441 中有可能不触发action方法,本人稍作改动。
UIWebView有自己的UIResgure,如果我们手动加入自己的GestureRecognize将不能识别,如UILongPressGestureRecongnizer. 在浏览网页的时候,如果看到喜欢的图片,想把它保存下来如何办呢? 我们可以自己写一个程序来实现,用uiwebview开发一个自己的浏览器。
关面说到uiwebview不能识别long press gesture,幸好有一个可以识别,那就是double click.因此我们注册它,代码如下:
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)]; doubleTap.numberOfTouchesRequired = 1; doubleTap.numberOfTapsRequired = 2; doubleTap.delegate = self; [self.webView addGestureRecognizer:doubleTap]; [doubleTap release];
然后就是实现doubleTap:
-(void)doubleTap:(UITapGestureRecognizer*) sender { // <Find HTML tag which was clicked by user> // <If tag is IMG, then get image URL and start saving> NSLog(@"doubleTap..........."); if(sender.numberOfTapsRequired == 2){ int scrollPositionY = [[self.webView stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] intValue]; int scrollPositionX = [[self.webView stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] intValue]; int displayWidth = [[self.webView stringByEvaluatingJavaScriptFromString:@"window.outerWidth"] intValue]; CGFloat scale = webView.frame.size.width / displayWidth; CGPoint pt = [sender locationInView:self.webView]; pt.x *= scale; pt.y *= scale; pt.x += scrollPositionX; pt.y += scrollPositionY; NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", pt.x, pt.y]; NSString * tagName = [self.webView stringByEvaluatingJavaScriptFromString:js]; NSLog(@"----------------js------%@",js); NSLog(@"----------------tagName------%@",tagName); if ([tagName isEqualToString:@"img"]||[tagName isEqualToString:@"IMG"]) { NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", pt.x, pt.y]; NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL]; NSLog(@"image url=%@", urlToSave); self.imgUrlPath = urlToSave; UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存图片至相册",nil]; [actionSheet setActionSheetStyle:UIActionSheetStyleDefault]; [actionSheet showInView:self.view.window]; [actionSheet release]; } } }
如果UITapGestureRecognizer不触发action就需要加入UITapGestureRecognizer的delegate中的一个方法:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; }