UIButton在自定义单元格中更改

时间:2013-11-09 12:46:56

标签: objective-c xcode uitableview uibutton

我正在使用此代码更改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"];
    }
}

1 个答案:

答案 0 :(得分: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];
}