【问题标题】:UIButton inside UIImageView does not respond to tapsUIImageView 内的 UIButton 不响应点击
【发布时间】:2011-09-04 02:17:09
【问题描述】:

我有一个滚动视图,它有一个带有图像作为子视图的图像视图,并且图像视图有一个 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];

【问题讨论】:

  • 您可以尝试看看bringSubviewToFront: 在将按钮添加到图像视图后是否有效?或者同样可以应用于滚动视图中的图像视图。
  • 事实上,我试过了,但没有成功。 userInteractionEnabled 成功了。

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


【解决方案1】:

UIImageView 默认将userInteractionEnabled 设置为NO/ false

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

【讨论】:

  • 酷,成功了。但是,当我这样做时,按钮的目标/操作方法被调用了两次(我在 buttonHandler 选择器中有一个 NSLog 来确认这一点)。为什么会这样?
  • 不应该UIControlEventAllEventsUIControlEventTouchUpInside
  • 确实是的!当我试图干预其他事情并忘记撤消更改时,我进行了更改。伟大的。谢谢!
  • 明智的话。!又名userInteractionEnabled
【解决方案2】:

请问您为什么要在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 图像映射类型的功能,其中单击图像的多个区域会执行不同的操作。
  • 我也试过了,但问题是当你放大和缩小地图时,按钮位置放错了位置,而你没有得到应有的点击动作。跨度>
【解决方案3】:

您可以将 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 上显示文本,使其可见。

这可能会解决您的问题。

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    相关资源
    最近更新 更多