我试图将触摸事件添加到从屏幕右侧到左侧漂移的小视图块中。问题是layer.presentationLayer hitTest:point
即使我确实在视图块的边界内轻按,方法也不会返回任何内容。
最后,我找到了一种解决方法。但是,两个问题仍然使我感到困惑。
presentationLayer hitTest
?UIViewAnimationOptionAllowUserInteraction
未设置,为什么我仍然可以处理触摸事件?以下是代码,任何帮助将不胜感激
viewDidLoad
CGRect bounds = [[UIScreen mainScreen] bounds];
for (int i = 0; i < 15; i++) {
ViewBlock *view = [[ViewBlock alloc] initWithFrame:CGRectMake(bounds.size.width, 200, 40, 40)];
[self.view addSubview:view];
[UIView animateWithDuration:20 delay:i * 21 options:UIViewAnimationOptionCurveLinear animations:^{
view.frame = CGRectMake(-40, 200, 40, 40);
} completion:^(BOOL finished) {
[view removeFromSuperview];
}];
}
@implementation ViewBlock
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor redColor];
}
return self;
}
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
CALayer *presentationLayer = self.layer.presentationLayer; //Do NOT modify presentationLayer
if (presentationLayer) {
CGPoint layer_point = [presentationLayer convertPoint:point fromLayer:self.layer.modelLayer];
if ([presentationLayer hitTest:point]) {
return self; //not worked
}
if ([presentationLayer hitTest:layer_point]) {
return self; //not worked either
}
if (CGRectContainsPoint(presentationLayer.bounds, layer_point)) {
return self; //the workaround
}
}
return [super hitTest:point withEvent:event];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[super touchesBegan:touches withEvent:event];
NSLog(@"touches began");
}
- (void)didMoveToSuperview{
[super didMoveToSuperview];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTouched:)]
;
tap.cancelsTouchesInView = NO;
[self addGestureRecognizer:tap];
}
- (void)tapTouched:(UITapGestureRecognizer *)sender{
NSLog(@"touches gesture");
}
@end
Q1:转换后的点似乎不正确,如何正确使用presentationLayer hitTest?
您所缺少的是参数hitTest:
应该在接收者的上层坐标系统中,因此代码应为:
CGPoint superLayerP = [presentationLayer.superlayer convertPoint:layer_point fromLayer:presentationLayer];
if ([presentationLayer hitTest:superLayerP]) {
return self;
}
Q2:在我的代码段中,未设置UIViewAnimationOptionAllowUserInteraction,为什么我仍然可以处理触摸事件
我认为您可以获取触摸事件,因为您可以覆盖- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
并返回self
结果,因此该事件将传递给它。默认情况下(如果不重写hitTest:withEvent:方法),将不会获得touch事件。
如果设置UIViewAnimationOptionAllowUserInteraction
选项,则可以在视图的最终帧(CGRectMake(-40,200,40,40))上获取触摸事件,但是在此示例中,最终帧不在屏幕上,您可以将其设置为CGRectMake(0, 200, 40, 40)
并具有一个测试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句