Ios 在多个UITableViewCell中更改UIButton图像

Ios 在多个UITableViewCell中更改UIButton图像,ios,objective-c,uitableview,uibutton,Ios,Objective C,Uitableview,Uibutton,我目前正在构建一个iOS应用程序,该应用程序使用带有自定义UITableViewCells(包括按钮)的UITableView。我想要完成的是在内部润色时更改UIButton的图像。这部分工作正常,问题是当您滚动时,UITableViewCell中的每几行按钮都会突然出现此新图像。下面是我的一些代码。任何帮助都将不胜感激 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPat

我目前正在构建一个iOS应用程序,该应用程序使用带有自定义UITableViewCells(包括按钮)的UITableView。我想要完成的是在内部润色时更改UIButton的图像。这部分工作正常,问题是当您滚动时,UITableViewCell中的每几行按钮都会突然出现此新图像。下面是我的一些代码。任何帮助都将不胜感激

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID = @"CellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];

        //YEP BUT
        yepBut = [[UIButton alloc] initWithFrame:CGRectMake(23, 16, 64, 32.5)];

        [yepBut addTarget:self action:@selector(yepPost:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:yepBut];
    }
    [yepBut setImage:[UIImage imageNamed:@"yepBtn"] forState:UIControlStateNormal];
    return cell;
}

-(void) yepPost:(id) sender{
    //UIButton *clicked = (UIButton *) sender;
    [sender setImage:[UIImage imageNamed:@"yepBtnACT"] forState:UIControlStateNormal];
}

谢谢

您需要在按下按钮时设置一个属性,以便签入cellForRowAtIndexPath。因此,在按钮的方法中,有一个属性,比如lastTouched(@property(strong,非原子)NSIndexPath*lastTouched,或者NSInteger(如果没有节),您可以将该属性设置为触摸按钮所在单元格的indexPath(或indexPath.row)(通过搜索按钮的超级视图直到找到该单元格,或通过在按钮上使用与indexath.row相等的标记,从该单元格中获取)。之后,必须重新加载数据或重新加载rowsatindexpath才能进行更改。在cellForRowAtIndexPath中,您可以如下设置图像:

if ([self.lastTouched isEqual:indexPath]) {
    [yepBut setImage:[UIImage imageNamed:@"yepBtnACT"] forState:UIControlStateNormal];
else{
    [yepBut setImage:[UIImage imageNamed:@"yepBtn"] forState:UIControlStateNormal];
}

当您第一次初始化LastTouch时,您希望将其设置为表中不出现的indexPath,这样,在您触摸一个之前,不会有yepButAct映像。

将UITableViewCell子类化解决了我的问题。

这似乎不起作用。它将if语句设置为true,但不会出于某种原因更改映像。知道为什么吗?@ZacharyChristopoulos,发生了什么事情?在if子句中设置映像后,尝试记录yepBut.imageForState,并查看它返回的内容。问题是dequeueReusableCellWithIdentifier。您需要更清楚地了解这一点。这将使内存(UITableViewCell)出列,您可能已经接触过了。因此,如果您在不退出队列的情况下尝试,代码应该可以正常工作。