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

Iphone 如何处理UITableView单元格中添加的UIButton上的触摸事件?,iphone,Iphone,我在UITableView的每个单元格上动态添加UIButton。我想处理此按钮上的触摸事件。你能帮我解决这个问题吗 提前感谢,, Vikas如果您在代码中完成所有操作 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; UITableVi

我在UITableView的每个单元格上动态添加UIButton。我想处理此按钮上的触摸事件。你能帮我解决这个问题吗

提前感谢,,
Vikas

如果您在代码中完成所有操作

- (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;
}


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

我在UITableView的DidSelectRowatineXpath方法中添加了此语句,但当我点击按钮时,它不会进入DidSelectRowatineXpath。如果我触摸UITableView按钮外的单元格/行,它将进入didSelectRowAtIndexPath内。我不明白为什么会发生这种情况?……如何解决?您可以在创建
UIButton
之后添加此目标,然后在单元格初始化时将该按钮添加到单元格中。
didselectrowatinexpath
方法用于响应点击单元格(行)本身,而不是按钮。此目标操作针对按钮本身。这更清楚吗?我想在UITableView的每个单元格上创建UIButton,当我单击该UIButton时,它应该会更改UIButton上的图像。那么,在哪里为每个单元格创建UIButton呢?下面的代码将使UITableView的每个单元格上的每个UIButton都可以使用。[myCellButton添加目标:自我操作:@选择器(myCellButton按下:)用于控制事件:UIControlEventTouchUpInside];
- (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];
}