前几天在做项目的时候,遇到这个一个问题,在一个视图也就是UIView上添加一个手势,然后又在这个View上添加一个UIButton,然后给按钮添加事件,运行项目的时候我发现,不管是点击按钮还是视图上的别的地方执行的都是手势所拥有的方法,后来到网上找才发现是手势把按钮的方法给屏蔽了,那怎么解决了正确的方法是给手势设置代理,然后在代理中进行判断如果点击事件是由Button执行的,那就不执行手势,那么系统会调用按钮所拥有的方法。具体的如下:
<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="objc"><span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="objc">UIView* showListView=[[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UITapGestureRecognizer* showTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showGes:)];
showTap.delegate=self;//设置代理 UITapGestureRecognizer的代理为UITapGestureRecognizerDelegate
tapGesture.cancelsTouchesInView = NO;//为NO时view的点击手势覆盖子视图响应,为YES时view的点击手势对其所有子视图无效
[showListView addGestureRecognizer:showTap];
[showTap release]; </pre><pre><span style="font-family: Arial, Helvetica, sans-serif;">//创建View上的button</span>
UIButton* btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(100.0,200.0,100.0,35.0);
[btn addTarget:self action:@selector(coverViewChoose:) forControlEvents:UIControlEventTouchUpInside];
[showListView addSubView:btn]; #pragma mark--UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if([touch.view isKindOfClass:[UIButton class]])
{
return NO;
}
return YES;
}
本文介绍了解决iOS开发中手势识别与按钮点击事件冲突的问题。通过设置手势识别器的代理并在代理方法中判断触碰事件是否由按钮触发来避免手势识别干扰按钮正常响应。
2619

被折叠的 条评论
为什么被折叠?



