如何处理添加到UITableView单元格上的UIButton的触摸事件?

9
我正在动态地在每个UITableView单元格上添加UIButton。我想要处理这个UIButton的触摸事件。请您帮忙解决这个问题吗?
谢谢, Vikas
2个回答

19
[myCellButton addTarget:self action:@selector(myCellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

我已经在UITableView的didSelectRowAtIndexPath方法中添加了这个语句,但是当我点击按钮时,它不会进入didSelectRowAtIndexPath。如果我点击UITableView的单元格/行上的按钮之外的区域,它会进入didSelectRowAtIndexPath。我不知道为什么会发生这种情况?......如何解决? - vikas Savardekar
你需要在创建UIButton之后添加此目标,然后在初始化单元格时将按钮添加到该单元格。didSelectRowAtIndexPath方法用于响应点击行本身(单元格/行),而不是按钮。这个目标动作是针对按钮本身的。现在清晰了吗? - Alex Reynolds
我想在UITabelView的每个单元格上创建UIButton,当我点击该UIButton时,它应更改UIButton上的图像。那么在哪里为每个单元格创建UIButton以及以下代码,以便它将适用于UITableView的每个单元格上的每个UIButton。[myCellButton addTarget:self action:@selector(myCellButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; - vikas Savardekar

0

如果你要全部用代码完成...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];        
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:@"Button" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(cellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [button sizeToFit];
        [cell.contentView addSubview:button];        
    }

    ...

    return cell;
}

...

- (IBAction)cellButtonPressed:(id)sender
{
    [sender setImage:[UIImage imageNamed:@"newImage"] forState:UIControlStateNormal];
}

但是我建议使用带有委托的UITableViewCell子类。


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