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

问题描述 投票:0回答:1

我正在尝试将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]返回零。你知道如何在不阻挡触摸的情况下捕获UIView上的水龙头和平底锅吗?非常感谢。

ios uiview uigesturerecognizer uitouch uievent
1个回答
1
投票

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

我的解决方案是

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

这是我检测触摸的@implementation DetectTouchWindow - (void)sendEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; switch ([touch phase]) { case UITouchPhaseBegan: NSLog(@"Touch Began"); break; case UITouchPhaseMoved: NSLog(@"Touch Move"); break; case UITouchPhaseEnded: NSLog(@"Touch End"); break; case UITouchPhaseCancelled: NSLog(@"Touch Cancelled"); break; default: break; } [super sendEvent:event]; } @end 的子类。我试过,它的工作原理。

https://github.com/trungducc/stackoverflow/tree/recording-touch-events

为了更详细和更容易,我创建了一个演示仓库来检查它。你可以看一下这个链接qazxswpoi

希望这可以帮助 ;)

© www.soinside.com 2019 - 2024. All rights reserved.