从自定义单元格更改图像

Change image from custoum cell

我有一个带有图像的自定义单元格,我只想在选中单元格时更改图像。

我正在尝试:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {


    if (!tableView.tag==0) {

        TableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell=[[TableViewCell2 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        }
   // cell.cam.image = [UIImage imageNamed:@"cam_normal.png"];
    cell.cam.highlightedImage = [UIImage imageNamed:@"cam_selected.png"];
    }
}

但图像没有改变。 这适用于正常细胞。

另一个尝试是在 cellForRowAtIndexPath

if (cell.selected==TRUE) {
            cell.cam.image=[UIImage imageNamed:@"cam_selected.png"];
        }

您已经将单元格作为参数获取,但在使用 dequeueReusableCellWithIdentifier 时获取另一个参数!

尝试这样的事情:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (!tableView.tag==0) 
    {
        TableViewCell2 *changeImageCell = (TableViewCell2*) cell;
        changeImageCell.cam.highlightedImage = [UIImage imageNamed:@"cam_selected.png"];
    }
}

你必须做两件事:

1。选择单元格后立即更改图像。

为此,您必须首先实施 UITableViewCell 委托。但是由于您已经 tableViewWillDisplayCel:forRowAtIndexPath:,我假设您已经实现了委托。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell2 *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.cam.highlightedImage = [UIImage imageNamed:@"cam_selected"];
}

当用户取消选择单元格时,您可以将图像改回原样。

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell2 *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.cam.highlightedImage = [UIImage imageNamed:@"cam_unselected"];
}

2。重复使用单元格时保留选择。

同样,当单元格被重复使用时,你必须检查它是否被选中。然后相应地分配图像。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell2 *cell = [tableView dequeReusableCellWithIdentifier:@"cell"];
    BOOL isRowSelected = [indexPath isEqaul:[tableView indexPathForSelectedRow]];
    if (isRowSelected) {
        cell.cam.highlightedImage = [UIImage imageNamed:@"cam_selected"];
    } else {
        cell.cam.hightlightedImage = [UIImage imageNamed:@"cam_unselected"];
    }
}

我注意到两件事。首先,你永远不要在 Objective-C 中使用 trueTRUE。您将 BOOLYESNO 一起使用。其次,你很少需要在 tableView:cellForRowAtIndexPath: 之外使用 dequeReusableCellWithIdentifier:。你为什么在那里做?