0

我正在使用此代码更改UIButton我的UITableView. 问题是当我滚动表格的按钮时,没有任何理由发生变化。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(232, 88, 78, 24)];

if([[array objectAtIndex:(indexPath.row)] isEqualToString:@"0"])
    [button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal];
else
    [button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal];

[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[Cell.contentView addSubview:button];

这是buttonClicked:方法:

-(void)buttonClicked:(id)sender
{
    CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.myTableView];
    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:touchPoint];
    UIButton *button = (UIButton *)sender;
    if([[array objectAtIndex:indexPath.row] isEqualToString:@"0"])
    {
        [button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal];
        [array replaceObjectAtIndex:indexPath.row withObject:@"1"];
    }
    else
    {
        [button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal];
        [array replaceObjectAtIndex:indexPath.row withObject:@"0"];
    }
}
4

1 回答 1

1

那是因为您的单元格正在被重复使用。试试这个:

    UIButton *button; = (UIButton *) [cell viewWithTag:34]; 
if (!button) {
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(232, 88, 78, 24)];
button.tag = 34; 

if([[array objectAtIndex:(indexPath.row)] isEqualToString:@"0"])
    [button setImage:[UIImage imageNamed:@"pic1"] forState:UIControlStateNormal];
else
    [button setImage:[UIImage imageNamed:@"pic2"] forState:UIControlStateNormal];

[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[Cell.contentView addSubview:button];
}
于 2013-11-09T12:50:50.310 回答