如何捕获UIButton事件:在自定义UITableViewCell实现中添加了UIButton



在著名的中,有一些关于如何将UIButton添加到UITableCellView的讨论

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

方法以及如何处理按钮单击。我对它们进行了测试,它们或多或少都很好。

我的设置略有不同。我想添加UIButton——事实上,我在不同的UIImageViews上有几个按钮——在我的自定义UITableCellView类中使用滑动触摸隐藏/显示。为了简单起见,我们假设只有一个UIImageView添加到单元格的视图堆栈中,并且只有一个UI按钮:

这是我的UITableViewCell实现的相关部分:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// sub menu
self.tableCellSubMenu = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320.0, 88.0)];
[self.tableCellSubMenu setImage:[UIImage imageNamed:@"cell_menu_back"]];
[self addSubview:self.tableCellSubMenu];
UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];                              
but.frame = CGRectMake(10.0, 0, 77.0, 88.0);
[but setImage:[UIImage imageNamed:@"cell_menu_icon_plus_up"] forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:@"cell_menu_icon_plus_down"] forState:UIControlStateSelected];
[but setImage:[UIImage imageNamed:@"cell_menu_icon_plus_down"] forState:UIControlStateHighlighted];
[but addTarget:self action:@selector(tableCellButtonPress:) forControlEvents:UIControlEventTouchUpInside];
[self.tableCellSubMenu addSubview:but];
...
}
return self;
}

UIButton被添加到UIImageView中,UIImageView又被添加到单元格的视图堆栈中。为了简单起见,我将按钮的目标配置为"self"。在我的实际设置中,目标是UITableViewController,我在其中处理按钮事件。我可以保证所有的设置都在工作(例如,用UIControl替换UIImageView,我们稍后会看到)。

不幸的是,在这种配置中,按钮上的内部修补事件不会触发。唯一被调用的函数是

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

在控制器中。通常,我会将UIButtons放在UIControl视图上。话虽如此,当我在上面的代码中用UIControl替换UIImageView时,按钮事件会按预期触发,但随后,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

不再接到电话。我两者都要。

如何让它发挥作用?

更新1:

我在自定义UITableViewCell实现中实现了以下方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint location = [((UITouch *)[touches anyObject]) locationInView:self];
if (CGRectContainsPoint(but.frame, location)) {
[self.touchButtonDelegate tableViewCellButtonTouched:self button:(UIButton*)but indexPath:self.touchButtonIndexPath];
}
[super touchesBegan:touches withEvent:event];
}

我仍在使用"UIImageView"对几个按钮进行分组和定位。

self.touchButtonDelegate是UITableViewController。这里提供了更完整的解决方案。

UIImageViews没有启用用户交互。您应该将其添加到单元格本身或其他UIView中。

最新更新