1

我正在尝试创建一个覆盖视图来监视触摸然后消失,但还将触摸事件转发到视图下方的任何内容。

我的测试应用程序有一个内部带有按钮的视图。我将覆盖视图添加为另一个子视图(本质上是按钮的兄弟),它占据了整个屏幕。

对于我尝试过的两种解决方案,叠加层会保持状态以确定它对触摸的响应方式。当收到 touchesBegan 事件时,overlay 将停止响应 hitTest 或 pointInside,直到收到 touchesCancelled 或 touchesEnded。

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if(_respondToTouch)
    {
        NSLog(@"Responding to hit test");
        return [super hitTest:point withEvent:event];
    }
    NSLog(@"Ignoring hit test");
    return nil;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if(_respondToTouch)
    {
        NSLog(@"Responding to point inside");
        return [super pointInside:point withEvent:event];
    }
    NSLog(@"Ignoring point inside");
    return NO;
}

对于我的第一种方法,我尝试重新发布该事件:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if(!_respondToTouch)
    {
        NSLog(@"Ignoring touches began");
        return;
    }
    NSLog(@"Responding to touches began");
    _respondToTouch = NO;

    [[UIApplication sharedApplication] sendEvent:event];
}

- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches cancelled");
    _respondToTouch = YES;
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches ended");
    _respondToTouch = YES;
}

但是,该按钮没有响应重新发布的事件。

我的第二种方法是使用 hitTest 来发现覆盖层下方的视图(我的按钮),然后直接向它发送 touchesXXX 消息:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches began");
    _respondToTouch = NO;
    UITouch* touch = [touches anyObject];
    _touchDelegate = [[UIApplication sharedApplication].keyWindow hitTest:[touch locationInView:self.superview] withEvent:event];
    CGPoint locationInView = [touch locationInView:_touchDelegate];
    NSLog(@"Sending touch %@ to view %@. location in view = %f, %f", touch, _touchDelegate, locationInView.x, locationInView.y);
    [_touchDelegate touchesBegan:touches withEvent:event];
}

- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches cancelled");
    [_touchDelegate touchesCancelled:touches withEvent:event];
    _respondToTouch = YES;
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches ended");
    [_touchDelegate touchesEnded:touches withEvent:event];
    _respondToTouch = YES;
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Touches moved");
    [_touchDelegate touchesMoved:touches withEvent:event];
}

它找到了按钮(根据日志),但是当我在其上调用 touchesXXX 时,按钮根本没有反应。

我不确定还能尝试什么,因为按钮不会响应直接调用 touchesBegan =/

4

0 回答 0