我有两个UIView
添加到ViewController
UITapGestureRecognizer
。它们的帧是碰撞的(假设它们相同以便于理解),当我点击UIView
时,我想触发两个视图的识别器功能,而不仅仅是最后添加为子视图的一个。有没有办法做到这一点?
用于创建UIViews和手势的代码:
UIView *a = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
UITapGestureRecognizer *aa =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDeviceClick:)];
[a addGestureRecognizer:aa];
[self.view addSubview:a];
UIView *b = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
UITapGestureRecognizer *bb =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDeviceClick:)];
[b addGestureRecognizer:bb];
[self.view addSubview:b];
功能:
-(void)handleDeviceClick:(UITapGestureRecognizer*)recognizer{
NSLog(@"device click occured");
}
UIGestureRecognizerDelegate
已添加到我的标题文件
答案 0 :(得分:0)
试试这个:
// second view is called
// handleDeviceClick1: action of second view
// handleDeviceClick0: action of first view
-(void)handleDeviceClick1:(UITapGestureRecognizer*)recognizer{
// call first view
[self handleDeviceClick0:recognizer]
}
答案 1 :(得分:0)
那你为什么不用
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = touches.anyObject;
CGPoint point = [touch locationInView:self.view];
您只需要检查点击的点是否在每个subViews
您不必创建两个UITapGestures
,如果您希望它们只使用一种方法就足够了。
您是否也将UIGestureRecognizerDelegate
添加到头文件中?
@interface ViewController <UIGestureRecognizerDelegate>
答案 2 :(得分:0)
您应该为您的手势识别器设置cancelsTouchesInView
至NO
,否则,检测触摸的第一个识别器将阻止第二个识别器执行此操作:
aa.cancelsTouchesInView = NO;
bb.cancelsTouchesInView = NO;
(实际上,您只需要为与顶级子视图关联的手势识别器执行此操作,但是如果您的视图层次结构可能会发生变化,则最好在两者上进行此操作。)
在docs:
中阅读cancelsTouchesInView
一个布尔值,用于影响在识别手势时是否将触摸传递到视图。
@property(nonatomic)BOOL cancelsTouchesInView
讨论
当此属性为YES(默认值)且接收器识别其手势时,该待处理手势的触摸不会传递到视图,并且先前传递的触摸将通过发送到视图的touchesCancelled:withEvent:消息取消。如果手势识别器无法识别其手势或此属性的值为“否”,则视图将接收多点触控序列中的所有触摸。