解决UICollectionView的Cell复用引起的布局混乱问题

首先创建一个可变数组,用来存放Cell的唯一标示符

// 用来存放Cell的唯一标示符
@property (nonatomic, strong) NSMutableDictionary *cellDic;
#warning 别忘了初始化哟
 self.cellDic = [[NSMutableDictionary alloc] init];

在cellForItemAtIndexPath:这个方法中作相应的一些处理即可,代码如下

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 每次先从字典中根据IndexPath取出唯一标识符
    NSString *identifier = [_cellDic objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
    // 如果取出的唯一标示符不存在,则初始化唯一标示符,并将其存入字典中,对应唯一标示符注册Cell
    if (identifier == nil) {
        identifier = [NSString stringWithFormat:@"%@%@", DayCell, [NSString stringWithFormat:@"%@", indexPath]];
        [_cellDic setValue:identifier forKey:[NSString stringWithFormat:@"%@", indexPath]];
        // 注册Cell
        [self.collectionView registerClass:[CalendarCollectionViewCell class]  forCellWithReuseIdentifier:identifier];
    }
 
    CalendarCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
 
// 此处可以对Cell做你想做的操作
 
    return cell;
}

发布了144 篇原创文章 · 获赞 166 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/autom_lishun/article/details/85061258