这个解决方案对我有用:
方法 1 - 检测自定义长按
A) 创建 UILongPressGestureRecognser 的子类。
B) 在子类中包含canBePreventedByGestureRecognizer: 方法,如下所示:
标题:
#import <UIKit/UIKit.h>
@interface CustomLongPress : UILongPressGestureRecognizer
@end
实施:
#import "CustomLongPress.h"
@implementation CustomLongPress
- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer*)preventedGestureRecognizer {
return NO;
}
@end
这是您在子类中唯一需要的代码。
C) 打开包含您的 uiwebview/pdf 阅读器的视图。包括您的子类:#import "CustomLongPress.h",然后将自定义 UILongPressGestureRecognser 添加到您的 UIWebView,如下所示:
- (void)viewDidLoad
{
[super viewDidLoad];
//Load UIWebView etc
//Add your custom gesture recogniser
CustomLongPress * longPress = [[CustomLongPress alloc] initWithTarget:self action:@selector(longPressDetected)];
[pdfWebView addGestureRecognizer:longPress];
}
D) 检测长按并关闭 UIWebView 的 userInteraction 然后再打开:
-(void)longPressDetected {
NSLog(@"long press detected");
[pdfWebView setUserInteractionEnabled:NO];
[pdfWebView setUserInteractionEnabled:YES];
}
显然,这是因为 UIWebView 使用自己的手势识别器捕获长按,排除您添加的任何其他手势识别器。但是将手势识别器子类化并通过向canBePreventedByGestureRecognizer: 方法返回“NO”来防止它们被排除在外,会覆盖默认行为。
一旦您可以检测到在 PDF 上的长按,将 userInteraction 关闭然后再打开会阻止 UIWebView 执行其默认行为,即启动“复制/定义”UIMenu,或者,如果长按链接,则启动弹出窗口- 带有“复制”和“打开”操作的操作表。
方法 2 - 捕捉 UIMenu NSNotification
或者,如果您只想阻止“复制/定义”UIMenu(但不影响长按),您可以将此行(监听 UIMenuControllerDidShowMenuNotification)添加到您的 ViewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuShown) name:UIMenuControllerDidShowMenuNotification object:nil];
然后添加此方法,使用与上面相同的 userInteraction Off/On 方法:
-(void)menuShown {
NSLog(@"menu shown");
[pdfWebView setUserInteractionEnabled:NO];
[pdfWebView setUserInteractionEnabled:YES];
}
第一种方法取自:https://devforums.apple.com/thread/72521?start=25&tstart=0,第二种方法取自 Stack 上的某个地方,抱歉忘记在哪里了。如果您知道,请提供。