在UIView上捕获和记录触摸事件

时间:2017-11-05 05:31:31

标签: ios uiview uigesturerecognizer uitouch uievent

我正在尝试将UIView子类化并设计透明视图。此视图将位于许多其他视图的顶部,它的唯一任务是捕获和记录用户触摸(点击和平移)。我尝试了很多不同的方法,在其他用户提出的不同问题中解释说没有运气。这是我到目前为止在我的实现文件中所做的:

#import "touchLayer.h"

@implementation touchLayer

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) [self commonInit];
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) [self commonInit];
    return self;
}

- (void)commonInit
{
    self.userInteractionEnabled = YES;
    self.alpha = 0.0;
}

- (id)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    id hitView = [super hitTest:point withEvent:event];
    if (hitView == self)
    {
        UITouch *touch = [[event allTouches] anyObject];

        if (touch.phase == UITouchPhaseBegan) NSLog(@"touchesBegan");
        else if (touch.phase == UITouchPhaseMoved) NSLog(@"touchesMoved");
        else if (touch.phase == UITouchPhaseEnded) NSLog(@"touchesEnded");

        return nil;
    }
    else
        return hitView;
}

@end

现在这段代码运行得很好,我看到了较低层的触摸,但我无法区分touchBegan,touchMoved和touchEnded。 [[event allTouches] anyObject]返回 nil 。你知道如何在不阻挡触摸的情况下捕获UIView上的水龙头和平底锅吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

经过调查,实际上我找不到使用hitTest方法touchLayer来检测触摸的解决方案。但你的问题是关于捕获和记录用户触摸,所以我有另一个问题。

我的解决方案是

  • 子类UIWindow
  • window的{​​{1}}替换为使用您的窗口类创建的新UIAppDelegate
  • 覆盖sendEvent的{​​{1}}方法,捕获并记录此方法中的用户触摸。

这是我UIWindow的子类来检测触摸。我尝试过它。

UIWindow

更多细节和更简单,我创建了一个演示仓库来检查它。您可以查看此链接https://github.com/trungducc/stackoverflow/tree/recording-touch-events

希望这会有所帮助;)

相关问题