我有一个响应触摸事件的 UIImage
视图。如果触摸移动到特定区域之外,我想要取消触摸序列,也就是不再调用 touchesMoved:
。如何实现呢?
我知道可以在 touchesMoved:
中检查触摸对象的坐标并忽略它,但我不知道如何彻底取消整个序列。在 苹果开发者的 UIResponder
参考文档 中,没有任何记录有关如何调用方法以取消触摸序列。
我有一个响应触摸事件的 UIImage
视图。如果触摸移动到特定区域之外,我想要取消触摸序列,也就是不再调用 touchesMoved:
。如何实现呢?
我知道可以在 touchesMoved:
中检查触摸对象的坐标并忽略它,但我不知道如何彻底取消整个序列。在 苹果开发者的 UIResponder
参考文档 中,没有任何记录有关如何调用方法以取消触摸序列。
- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
我基于在苹果iPhone示例代码网站上对MoveMe示例应用程序所做的一些调整,提出了这个解决方案。我修改了touchesMoved
方法,使其看起来像这样:
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch view] == placardView)
CGPoint location = [touch locationInView:self];
placardView.center = location;
// I added the following line:
[self touchesCancelled:touches withEvent:event];
return;
}
尝试将UIImageView的userInteractionEnabled属性临时设置为NO。
为了让父视图从事件中清理出来,您需要调用[super touchesMoved:withEvent:]
,但更重要的是,您不需要调用[super touchesCancelled:withEvent:]
。
这是我在检测到滑动时用于防止单元格被选中的代码:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!showingEdit) {
if (IS_FAR_ENOUGH_TO_BE_A_SWIPE) {
RESPOND_TO_SWIPE
showingEdit = YES;
[super touchesCancelled:touches withEvent:event];
} else {
[super touchesMoved:touches withEvent:event];
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!showingEdit) {
[super touchesEnded:touches withEvent:event];
}
}
最近我也遇到了同样的问题,并找到了一个标准的解决方法。 您可以使用[[UIApplication sharedApplication] beginIgnoringInteractionEvents]停止将touchesMoved事件传递给整个应用程序。请确保在需要再次接收触摸时使用[[UIApplication sharedApplication] endIgnoringInteractionEvents]来启用它们。
[view retain];
UIView *sv = view.superview;
[view removeFromSuperview];
[sv addSubview:view];
[view release];
我刚试着解决类似这样的问题,但发现这里列出的解决方案都对我无效。我最好的方法是暂时忽略触摸,但当触摸重新进入视图时它们又会继续。
最后终于解决了。
我想,除非你有特定需要确切取消触摸序列,否则这个解决方案对你很有用。
-(void)setSentTouchesEnded:(BOOL)ended;
根据苹果的实现,它可能会停止发送事件
另一种方法是使用关联对象
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([(NSNumber *)objc_getAssociatedObject(touch, &outKey) boolValue])
return;
if (sometouchisoutsideofview) {
objc_setAssociatedObject(touch, &outKey, [NSNumber numberWithBool:YES], OBJC_ASSOCIATION_RETAIN);
}
}
touchesMoved:
方法中禁用了触摸事件,并在touchesCancelled:
方法中启用了触摸事件。-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
.......
.......
Your code
.......
.......
//Condition when you want to disable touch event
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
.......
.......
Your code
.......
.......
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}