为什么UIButton没有响应触摸?

11

我看了很多回复,但仍然无法理解。我知道第一行有点奇怪,但这是因为它继承了一个设置表头视图为搜索栏的超类。

searchBar = (UISearchBar *)self.tableView.tableHeaderView;
[[searchBar.subviews objectAtIndex:0] removeFromSuperview];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, -100, self.view.frame.size.width, 100)];
label.text = @"AAAA";
[searchBar addSubview:label];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
           action:@selector(aMethod)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, -60, 160.0, 40.0);

searchBar.exclusiveTouch = NO;
searchBar.userInteractionEnabled = NO;
label.userInteractionEnabled = NO;
button.userInteractionEnabled = YES;
[searchBar insertSubview:button atIndex:3];

尝试设置 searchBar.userInteractionEnabled = YES; 而不是其他。 - Valent Richie
我已经尝试过了,但它并不起作用。 - mergesort
也尝试过,但不起作用。 - mergesort
2个回答

10

如果在父视图上将userInteractionEnabled设置为NO,它会级联到所有子视图。因此,您的UIButton实例将显示不响应,因为searchBar已被禁用。


即使我删除了searchbar.exclusive touch和searchbar.userinteractionenabled,它仍然无法正常工作。 - mergesort

9
这是你的答案: searchBar.userInteractionEnabled = NO; 如果您要向已禁用用户交互的视图添加子视图,则该子视图将无法接收触摸。我没有仔细查看您的代码,以查看是否有其他错误。
首先看一下框架:
button.frame = CGRectMake(80.0,-60,160.0,40.0); UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,-100,self.view.frame.size.width,100)];
按钮和标签都不可见,这些对象被放在边界之外,这就是为什么您无法触摸它们的原因。请注意,保留了html标记。

是的,它们被放置在边界之外。触摸事件不能发送到超出边界的对象吗?它们仍然可见,因为我正在以偏移量显示表视图。编辑:这个方法有效。 - mergesort
不,这里无法发送触摸信息,就像你试图将屏幕右侧的图像移动并只看到一个角落一样,你正在尝试查看外面的内容。我曾在WWDC上与一位iOS工程师讨论过这个问题。 - soryngod
显然,如果你重写一个方法,这是可以做到的。但在这种情况下不值得这样做。谢谢。 - mergesort
我认为你指的是hitTest。但是,确实不值得。 - soryngod
哇,子视图边界观察非常准确!!!我已经将子视图的背景颜色更改为红色,并立即发现包含不响应的UISwitch的子视图高度为0点(无处可寻)。当我调整子视图的底部约束以匹配UISwitch的高度时,UISwitch开始响应轻拍。 - timmi4sa

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