轉載自: http://zl4393753.iteye.com/blog/1752135
UIWebView長按圖片產生儲存菜單
參考:
http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/
http://www.icab.de/blog/2011/10/17/elementfrompoint-under-ios-5/comment-page-1/#comment-30184
自訂UILongPressGestureRecognizer
建立 UnpreventableUILongPressGestureRecognizer.h
C代碼 #import <Foundation/Foundation.h> @interface UnpreventableUILongPressGestureRecognizer : UILongPressGestureRecognizer { } @end
UnpreventableUILongPressGestureRecognizer.m
C代碼 #import "UnpreventableUILongPressGestureRecognizer.h" @implementation UnpreventableUILongPressGestureRecognizer - (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer { return NO; } @end
UIWebview頁面給webview添加手勢 ViewController.m:
C代碼 UnpreventableUILongPressGestureRecognizer *longPressRecognizer = [[UnpreventableUILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; longPressRecognizer.allowableMovement = 20; longPressRecognizer.minimumPressDuration = 1.0f; [webview addGestureRecognizer:longPressRecognizer];
ViewController.m 處理手勢:
C代碼 -(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer { if (gestureRecognizer.state == UIGestureRecognizerStateBegan) { CGPoint pt = [gestureRecognizer locationInView:self.webview]; // convert point from view to HTML coordinate system // 뷰의 포인트 위치를 HTML 좌표계로 변경한다. CGSize viewSize = [webview frame].size; CGSize windowSize = [webview windowSize]; CGFloat f = windowSize.width / viewSize.width; if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 5.0) { pt.x = pt.x * f; pt.y = pt.y * f; } else { // On iOS 4 and previous, document.elementFromPoint is not taking // offset into account, we have to handle it CGPoint offset = [webview scrollOffset]; pt.x = pt.x * f + offset.x; pt.y = pt.y * f + offset.y; } [self openContextualMenuAt:pt]; } }
建立分類 WebViewAdditions.h
C代碼 #import <foundation foundation.h=""> @interface UIWebView(WebViewAdditions) - (CGSize)windowSize; - (CGPoint)scrollOffset; @end </foundation>
WebViewAdditions.m
C代碼 #import "WebViewAdditions.h" @implementation UIWebView(WebViewAdditions) - (CGSize)windowSize { CGSize size; size.width = [[self stringByEvaluatingJavaScriptFromString:@"window.innerWidth"] integerValue]; size.height = [[self stringByEvaluatingJavaScriptFromString:@"window.innerHeight"] integerValue]; return size; } - (CGPoint)scrollOffset { CGPoint pt; pt.x = [[self stringByEvaluatingJavaScriptFromString:@"window.pageXOffset"] integerValue]; pt.y = [[self stringByEvaluatingJavaScriptFromString:@"window.pageYOffset"] integerValue];