我正在尝试检测用户何时在视图中向下触摸。该视图包含一些按钮和其他UIKit控件。我想检测这些触摸事件但不消耗它们。
我尝试了两种方法,但两种方法都不够:
首先,我添加了一个透明覆盖覆盖--touchesBegan:withEvent:和-touchesEnded:withEvent:并使用
将事件转发给下一个响应者[self.nextResponder touchesBegan:touches withEvent:event]
但是,似乎UIKit对象忽略了所有转发的事件。
接下来,我尝试重写-pointInside:withEvent:和-hitTest:withEvent :.这对于检测触摸 down 事件非常有用,但是在触摸 up 时没有调用pointInside ::和hitTest ::([[[all allTouches] anyObject]阶段]是永远不等于UITouchPhaseEnded。。
在不干扰与底层UIControl的交互的情况下,检测触地和触摸事件的最佳方法是什么?
答案 0 :(得分:-1)
根据Event Handling Guide for iOS 你有3个选择:
1)继承UIWindow以覆盖sendEvent:
2)使用叠加视图
3)设计,这样你就不必这样做......所以更像是2个选项。
以下是使用UIWindow子类的Apple示例的简化;
1)将NIB中窗口的类更改为UIWindow的子类。 2)将此方法放在.m文件中。
- (void)sendEvent:(UIEvent *)event
{
NSSet * allTouches = [event allTouches];
NSMutableSet *began = nil;
NSMutableSet *moved = nil;
NSMutableSet *ended = nil;
NSMutableSet *cancelled = nil;
// sort the touches by phase so we can handle them similarly to normal event dispatch
for(UITouch *touch in allTouches) {
switch ([touch phase]) {
case UITouchPhaseBegan:
if (!began) began = [NSMutableSet set];
[began addObject:touch];
break;
case UITouchPhaseMoved:
if (!moved) moved = [NSMutableSet set];
[moved addObject:touch];
break;
case UITouchPhaseEnded:
if (!ended) ended = [NSMutableSet set];
[ended addObject:touch];
break;
case UITouchPhaseCancelled:
if (!cancelled) cancelled = [NSMutableSet set];
[cancelled addObject:touch];
break;
default:
break;
}
// call our methods to handle the touches
if (began)
{
NSLog(@"the following touches began: %@", began);
};
if (moved)
{
NSLog(@"the following touches were moved: %@", moved);
};
if (ended)
{
NSLog(@"the following touches were ended: %@", ended);
};
if (cancelled)
{
NSLog(@"the following touches were cancelled: %@", cancelled);
};
}
[super sendEvent:event];
}
它有太多的输出,但你会得到这个想法......并且可以使你的逻辑适合你想要的地方。