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];
默认情况下,UIImageViewuserInteractionEnabled设置为NO/false

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

请问您为什么要在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];

您可以将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];因为它用于在CCD_ 15上显示使其可见的文本。

这可能会解决您的问题。