ios 将单击手势添加到超级视图时 UIButton 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4643513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:29:06  来源:igfitidea点击:

UIButton not working when single tap gesture is added to superview

iphoneiosuibuttonsubviewuigesturerecognizer

提问by Andrew

I have a UIButton set up and hooked up to an action in my view controller as usual. Just this by itself works fine.

我有一个 UIButton 设置并像往常一样连接到我的视图控制器中的一个动作。仅此而已就可以正常工作。

Now, I have added the following to my view controller to set up a single tap:

现在,我已将以下内容添加到我的视图控制器中以设置单击:

- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer * singleTapGesture = [[UITapGestureRecognizer alloc] 
                                             initWithTarget:self
                                             action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleTapGesture];
[singleTapGesture release]; }

Now, every time I tap the button it looks like it was tapped but it fires the gesture recognizer code instead of the button action.

现在,每次我点击按钮时,它看起来都被点击了,但它会触发手势识别器代码而不是按钮操作。

How can I make it so that the button works when I tap the button and the tap gesture works when I tap anywhere else in the view?

我怎样才能让按钮在我点击按钮时工作,而在我点击视图中的任何其他地方时点击手势工作?

采纳答案by vdaubry

Your problem is similar to this question which hopefully has been answered ;)

您的问题与此问题类似,希望已得到解答;)

UIButton inside a view that has a UITapGestureRecognizer

具有 UITapGestureRecognizer 的视图内的 UIButton

回答by ragnarius

Here is a simple solution

这是一个简单的解决方案

singleTapGesture.cancelsTouchesInView = NO;

回答by Robin

Andrew,

安德鲁,

It seems to me that you want to call a function when the user taps any where except the UI objects.

在我看来,当用户点击除 UI 对象之外的任何位置时,您想调用一个函数。

so my suggestion is that create a custom button of the size of screen(320x460 assuming that the grey bar is shown) place it back of all the objects in the IB. By this time you will be able to see a UIButton with almost 0% opacity.

所以我的建议是创建一个屏幕大小的自定义按钮(假设显示灰色条为 320x460)将它放回 IB 中的所有对象。到这个时候,你将能够看到一个几乎为 0% 不透明度的 UIButton。

and from the IB drag the selector option of the custom button to the file owners and select the function that you want to call and you are all done.

并从 IB 中将自定义按钮的选择器选项拖到文件所有者并选择要调用的函数,然后就大功告成了。

Its simpler than what you were attempting in your code

它比您在代码中尝试的更简单