在didSelectRow方法中使用单元格(从cellForRow方法返回)

时间:2012-10-01 09:23:56

标签: iphone objective-c

我被困在一个我想在图像按钮顶部添加图像的地方,以便当我点击它时按钮的图像会发生变化。我必须在didSelectRow方法中编写逻辑。因此,我需要编写以下行来添加该图像:

button=[UIButton alloc] initWithFrame:CGRectMake(230,0,40,40];
button.addTarget: self action: @selector(buttonPressed:withEvent:) forControlEvents:UIControlEventTouchUpInside];
button.tag=indexPath.row;
[button setImage: [UIImage imageNamed:@"a.png"] forState:UIControlStateNormal];
[cell addSubview: button];

虽然这在我在cellForRow中编写上述代码时有效,但这在didSelectRow中不起作用,因为此方法中未定义单元格。

2 个答案:

答案 0 :(得分:0)

在didSelectRow中尝试获取单元格

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

答案 1 :(得分:0)

试试这个

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{  

    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    for (UIButton *button in cell.subviews) {
        if (button.tag==indexPath.row) {
            [button setImage: [UIImage imageNamed:@"another.png"] forState:UIControlStateNormal];
        }
    }
}