iOS失去了什么?

Joe*_*man 8 iphone multi-touch ios uievent

我找不到任何解释丢失的UITouch事件的东西.如果你在屏幕上粉碎你的整个手足够多次,touchesBegan的数量将不同于touchesEnded的数量!我认为实际了解这些孤立触摸的唯一方法是自己引用它们并跟踪它们没有移动多长时间.

示例代码:

int touchesStarted = 0;
int touchesFinished = 0;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    touchesStarted += touches.count;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    touchesFinished += touches.count;
    NSLog(@"%d / %d", touchesStarted, touchesFinished);
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 5

不要忘记touchesCancelled:UIResponder参考

编辑以响应海报的更新:

每个触摸对象提供它所处的阶段:

typedef enum {
    UITouchPhaseBegan,
    UITouchPhaseMoved,
    UITouchPhaseStationary,
    UITouchPhaseEnded,
    UITouchPhaseCancelled,
} UITouchPhase;
Run Code Online (Sandbox Code Playgroud)

我相信,如果触摸在同一触摸事件集中开始和结束,-touchesBegan:withEvent:将被调用,但将包含已结束或取消的触摸.

您应该更改您的计数代码,然后,看起来像这样:

int touchesStarted = 0;
int touchesFinished = 0;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self customTouchHandler:touches];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self customTouchHandler:touches];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self customTouchHandler:touches];
}
- (void)customTouchHandler:(NSSet *)touches
{
    for(UITouch* touch in touches){
        if(touch.phase == UITouchPhaseBegan)
            touchesStarted++;
        if(touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled)
            touchesFinished++;
    }
    NSLog(@"%d / %d", touchesStarted, touchesFinished);
}
Run Code Online (Sandbox Code Playgroud)

每个触摸事件都将经历启动和完成/取消的两个阶段,因此一旦您的手指离开屏幕,您的计数应该匹配.