在UIWebview上,我该如何检测触摸?
但不是在用户点击某个网址或触摸控件时。
是否可以处理它?</ p>
答案 0 :(得分:34)
使用UIGestureRecognizerDelegate方法:
在声明文件中添加UIGestureRecognizerDelegate(即您的.h文件)
步骤1:设置gestureRecognizer的委托:(在.m文件viewDidLoad中)
UITapGestureRecognizer *webViewTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
webViewTapped.numberOfTapsRequired = 1;
webViewTapped.delegate = self;
[offScreenWebView addGestureRecognizer:webViewTapped];
[webViewTapped release];
步骤2:覆盖此功能:(在.m文件中)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
步骤3:现在实现tapAction功能:
- (void)tapAction:(UITapGestureRecognizer *)sender
{
NSLog(@"touched");
// Get the specific point that was touched
CGPoint point = [sender locationInView:self.view];
}
答案 1 :(得分:2)
如果您只需要检测水龙头,那么接受的答案就很棒。如果需要检测所有触摸,最好的方法是创建一个新的UIView子类并将其放在webview上。在子类中,您可以使用hitTest检测触摸:
TouchOverlay.h
@class TouchOverlay;
@protocol TouchOverlayDelegate <NSObject>
@optional
- (void)touchOverlayTouched:(TV4TouchOverlay *)touchOverlay;
@end
@interface TouchOverlay : UIView
@property (nonatomic, unsafe_unretained) id <TouchOverlayDelegate> delegate;
@end
Touchoverlay.m
@implementation TouchOverlay
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
return self;
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
UIView *hitView = [super hitTest:point withEvent:event];
if (hitView == self) {
if (self.delegate && [self.delegate respondsToSelector:@selector(touchOverlayTouched:)]) {
[self.delegate touchOverlayTouched:self];
}
return nil; // Tell the OS to keep looking for a responder
}
return hitView;
}
@end
答案 2 :(得分:1)
请注意,上面接受的答案只会捕获点按手势(touchDown和touchUp之间没有拖动),并且会忽略滑动手势。
出于我的目的,我需要被告知两者,因此我适当地添加了滑动手势识别器。 (请注意,尽管是一个位字段,但您可以OR
一起轻扫手势识别器&#39; direction
属性,因此需要4个手势识别器来检测任何滑动。)
// Note that despite being a bit field, you can't `OR` together swipe gesture
// recognizers' `direction` property, so 4 gesture recognizers are required
// to detect any swipe
for (NSNumber * swipeDirection in @[@(UISwipeGestureRecognizerDirectionUp), @(UISwipeGestureRecognizerDirectionDown), @(UISwipeGestureRecognizerDirectionLeft), @(UISwipeGestureRecognizerDirectionRight)]) {
UISwipeGestureRecognizer * swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(timerReset:)];
swipe.direction = [swipeDirection integerValue];
swipe.delegate = self;
[rootWebView addGestureRecognizer:swipe];
}
答案 3 :(得分:0)
从UIResponder继承的所有内容都可以处理触摸(UIWebView也是如此)。阅读文档: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIResponder_Class/Reference/Reference.html
你必须使用:
touchesBegan:withEvent:
修改:为了清晰起见,请在此处添加评论
我相信那时没有干净的方法,你可以覆盖像this这样的事件方法,或者做一个像这样的黑客攻击:overriding UIView
答案 4 :(得分:-1)
你的意思是你想要覆盖他们按住链接时弹出的选项吗?我设法让一个人使用这个教程/指南,但是这里发布的一个仍然有点错误,需要你做一些微调: http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/