UIImageView内的UIButton不响应点击

时间:2011-05-28 21:08:54

标签: ios objective-c cocoa-touch uiimageview uibutton

我有一个滚动视图,其中包含一个图像视图,图像作为子视图,图像视图的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];

3 个答案:

答案 0 :(得分:90)

默认情况下,

UIImageView userInteractionEnabled设置为NO / false

您要将按钮作为子视图添加到图像视图中。您应该将其设置为YES / true

答案 1 :(得分:4)

我可以问你为什么要为UIButtons添加隐身UIImageView

似乎是一种不好的做法,请注意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];

答案 2 :(得分: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上显示使其可见的文本。

这可能会解决您的问题。