我正在尝试子类化 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 上的点击和平移吗?非常感谢。
最佳答案
经过调查,实际上我无法找到使用带有 touchLayer
的 hitTest
方法来检测触摸的解决方案。但你的问题是关于捕获和记录用户触摸,所以我有另一个问题。
我的解决方案是
- 子类
UIWindow
- 将
UIAppDelegate
的window
替换为使用您的窗口类创建的新窗口。 - 重写
UIWindow
的sendEvent
方法,在该方法中捕获并记录用户触摸。
这是我的 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/