UIImageView内部的UIButton无法响应点击

35

我有一个滚动视图,其中包含一个图像视图作为子视图,并且该图像视图具有一个UIButton作为其子视图之一。 问题是,我无法点击按钮。 我可以看到按钮,但无法轻触它。

有人能告诉我我错了什么吗? 非常感谢任何帮助! 谢谢!

以下是代码:

scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];    
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img.jpg"]];
scrollView.delegate = self;
self.view = scrollView;

// add invisible buttons
[self addInvisibleButtons];
[scrollView addSubview:imageView];

addInvisibleButtons 的代码如下:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents];
[button setTitle:@"point" forState:UIControlStateNormal];
button.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
[self.imageView addSubview:button];

1
你可以尝试在将按钮添加到图像视图后使用 bringSubviewToFront: 方法,看看是否有效?或者同样的方法也可以应用于滚动视图中的图像视图。 - Luke
事实上,我尝试过那个方法,但它没有起作用。userInteractionEnabled才是解决问题的关键。 - Ravi
3个回答

101

UIImageView默认情况下将userInteractionEnabled设置为NO/false

您正在将按钮添加为图像视图的子视图。 您应该将其设置为YES/true


1
太棒了,行了。但是,当我这样做时,按钮的目标/操作方法被调用了两次(我在“buttonHandler”选择器内使用NSLog进行了确认)。为什么会发生这种情况? - Ravi
3
“UIControlEventAllEvents” 应该改为 “UIControlEventTouchUpInside” 吗? - Deepak Danduprolu
确实是这样!我在尝试干涉其他事情时做了这个更改,忘记撤消了。太好了。谢谢! - Ravi
明智的话语!又称为userInteractionEnabled - Yash Bedi

4

您为什么要在UIImageView中添加不可见的UIButtons

这似乎是一种不好的做法,需要注意的是Interface Builder不允许您在其中添加UIButton

如果您想要一个带有触摸处理的图像,您可以:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents];
[button setTitle:@"point" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"img.jpg"] forState:UIControlStateNormal];
[button setFrame:CGRectMake(0.0, 0.0, 40.0, 40.0)];

[scrollView addSubview:button];

因为我想在iPad上实现HTML图像映射的功能,即单击图像的几个区域会执行不同的操作。 - Ravi
我已经尝试过那个方法,问题在于当你放大和缩小地图时,按钮位置会错位,导致你无法在预期的位置进行点击操作。 - Ravi

2
您可以将 addInvisibleButtons 实现为:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundColor:[UIColor clearColor]];
[button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents];
[button setTitle:@"point" forState:UIControlStateNormal];
button.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
self.imageView.userInteractionEnabled = YES;
[self.imageView addSubview:button];

如果你想让UIButton完全不可见,那么你需要删除一行代码[button setTitle:@"point" forState:UIControlStateNormal];。因为它用于在UIButton上显示文本,从而使其可见。
这可能会解决你的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接