可重用的UICollectionViewCell不刷新

时间:2017-01-11 06:29:26

标签: ios objective-c uicollectionview uicollectionviewcell uicollectionreusableview

我的UICollectionViewCell在故事板中有一个按钮,从文档目录中动态设置按钮数量的背景图像创建问题,如某些按钮背景图像不刷新,即使我关闭控制器并再次加载控制器,它们也会保留旧图像,这个问题依然存在。怎么能解决这个问题?

在我的CollectionViewController中:

- (NSString *)getBackgroundImage:(NSIndexPath *)indexPath {

    NSArray *indexes = [self.allColors[indexPath.section] objectForKey:@"indexes"];

    return [NSString stringWithFormat:@"%@/%@/%@/combimeter_button/combimeter_%ld_%@@2x.png", [self.documentDirectory getDocumentsDirectory], _selectedCar, _selectedCar, (long)[indexes[indexPath.row] integerValue], [self getColorKey:indexPath.section]];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CustomCollectionViewCell *cell = (CustomCollectionViewCell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];

    cell.layer.borderWidth = 2.0f;
    cell.layer.borderColor = [[self getBackgroundColor:indexPath.section] CGColor];
    [cell.cellButton setBackgroundImage:[UIImage imageNamed:[self getBackgroundImage:indexPath]] forState:UIControlStateNormal];
    [cell.cellButton addTarget:self action:@selector(combimeterButtonDidSelected:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

在我的自定义collectionView Cell中:

@interface CustomCollectionViewCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UIButton *cellButton;

@end

@implementation CustomCollectionViewCell

-(void)prepareForReuse {
    NSLog(@"Is it possible to clear here ? but this method didn't call in my code");
}

@end

2 个答案:

答案 0 :(得分:2)

问题可能是imageNamed:缓存了图像。请尝试使用imageWithContentsOfFile:

答案 1 :(得分:0)

在创建新视图之前尝试删除所有先前的视图:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CustomCollectionViewCell *cell = (CustomCollectionViewCell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];

    for (UIView *subview in [cell subviews]) {
        [subview removeFromSuperview];
    }

    ...
}