ios - 捕获并记录 UIView 上的触摸事件

标签 ios uiview uigesturerecognizer uitouch uievent

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

#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 上的点击和平移吗?非常感谢。

最佳答案

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

我的解决方案是

  • 子类UIWindow
  • UIAppDelegatewindow 替换为使用您的窗口类创建的新窗口。
  • 重写UIWindowsendEvent方法,在该方法中捕获并记录用户触摸。

这是我的 UIWindow 子类,用于检测触摸。我试过了,它起作用了。

@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

为了更详细和更容易,我创建了一个演示 repo 来检查它。你可以看一下这个链接https://github.com/trungducc/stackoverflow/tree/recording-touch-events

希望这有帮助;)

关于ios - 捕获并记录 UIView 上的触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47118505/

相关文章:

ios - swift 表格 View 中的字母部分

ios - 在 iDevice 上运行 Swift XCTests

ios - 在 awakeFromNib() 上 - 错误实例成员 'button' 不能在类型 'CustomView' 上使用

ios - 仅在触摸有颜色的部分时才拖动对象或 ImageView

iPhone通过手指运动识别不同的形状

ios - 读取 csv 文件 ios

ios - react-native run-ios 构建卡住

ios - 在 UIView 中居中 UIImageView

ios - UIView transitionFromView 改变 View 高度

swift - 使用 UIPanGestureRecognizer 的输入实现自然滚动算法