1

我正在尝试检测用户何时在视图中向下和向上触摸。该视图包含一些按钮和其他 UIKit 控件。我想检测这些触摸事件但不消耗它们。

我尝试了两种方法,但都不够:

首先,我添加了一个透明覆盖覆盖 -touchesBegan:withEvent: 和 -touchesEnded:withEvent: 并将事件转发给下一个响应者

[self.nextResponder touchesBegan:touches withEvent:event]

然而,UIKit 对象似乎忽略了所有转发的事件。

接下来,我尝试覆盖 -pointInside:withEvent: 和 -hitTest:withEvent: 。这对于检测触地事件非常有效,但是在触地时不会调用 pointInside:: 和 hitTest:: (即 [[[event allTouches] anyObject] 阶段] 永远不会等于 UITouchPhaseEnded )。

在不干扰与底层 UIControls 交互的情况下,检测 touch down 和 touch up 事件的最佳方法是什么?

4

1 回答 1

-1

根据iOS 的事件处理指南, 您有 3 个选项:

1) 继承 UIWindow 以覆盖 sendEvent:

2) 使用覆盖视图

3)设计,这样你就不必这样做......所以真的更像是2个选项。

这是一个简化的苹果示例,使用 UIWindow 子类;

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];
}

它有太多的输出,但你会明白的......并且可以使你的逻辑适合你想要的地方。

于 2011-06-17T23:20:16.167 回答