在自定义UITableviewCell中设置图像不会*坚持*



我有一个自定义的UITabvleViewCell,里面有一个UIImageView。 当单元格在cellForRowAtIndexPath中设置时,我可以很好地设置图像(尽管我没有),但是在某些情况下,我需要更改图像,并且一直使用以下代码执行此操作。

-(void)updateCellForUPC
{
    AppData* theData = [self theAppData];
    NSInteger cellIndex;
    for (cellIndex = 0; cellIndex < [productArray count]; cellIndex++) {
      NSString *cellUPC = [NSString stringWithFormat:@"%@",[[productArray objectAtIndex:cellIndex] objectForKey:@"UPC"]];
        if ([cellUPC isEqualToString:theData.UPC]) {
            OrderDetailCell *activeCell = [[OrderDetailCell alloc] init];
            activeCell = (OrderDetailCell *) [orderDetailTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:cellIndex inSection:0]];
            UIImage* image = [UIImage imageNamed:@"checkmark.png"];
            activeCell.statusImageView.image = image;
            activeCell.checked = YES;
        }
    }
}

这有效并且图像会更新,但是当您将单元格从屏幕上滚动回屏幕上时,图像会重置!

我需要它*坚持新图像。

不建议这样做,因为您没有获得未使用单元格的取消排队机制的好处。请考虑在创建单元时执行此操作,或创建一种机制来了解应对哪些单元格执行此操作。

对于任何对我将来如何做到这一点感兴趣的人。

我做了一个NSMutableArray,并将索引添加为NSString。如果当时显示单元格,我还设置了该单元格的图像。

-(void)updateCellForUPC
{
    AppData* theData = [self theAppData];
    NSInteger cellIndex;
    for (cellIndex = 0; cellIndex < [productArray count]; cellIndex++) {
      NSString *cellUPC = [NSString stringWithFormat:@"%@",[[productArray objectAtIndex:cellIndex] objectForKey:@"UPC"]];
        if ([cellUPC isEqualToString:theData.UPC]) {
            OrderDetailCell *activeCell = [[OrderDetailCell alloc] init];
            activeCell = (OrderDetailCell *) [orderDetailTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:cellIndex inSection:0]];
            UIImage* image = [UIImage imageNamed:@"checkmark.png"];
            activeCell.statusImageView.image = image;
            NSString *index = [NSString stringWithFormat:@"%d",cellIndex];
            [selectionArray addObject:index];
        }
    }
}

然后在我的cellForRowAtIndexPath中,我只使用以下代码来检查索引是否在数组中,如果它是,则设置我的图像。这样,当单元格被重绘(滚动)时,它就有了图像。

NSString *index = [NSString stringWithFormat:@"%d",indexPath.row];
if ([selectionArray containsObject:index]) {
    UIImage* image = [UIImage imageNamed:@"checkmark.png"];
    cell.statusImageView.image = image;
}

最新更新