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

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

 

问题复现.gif


查了一下度娘发现没有好的解决办法,于是发动自己的聪明才智,终于找到如下解决办法(充分证明了自己动手丰衣足食啊😄)

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

    // 用来存放Cell的唯一标示符
    @property (nonatomic, strong) NSMutableDictionary *cellDic;
    #warning 别忘了初始化哟
     self.cellDic = [[NSMutableDictionary alloc] init];
  2. 在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;
}

修改之后的效果图如下所示


修改之后的效果图.gif
posted @ 2017-10-29 15:22  神来钥匙-陈诗友  阅读(7255)  评论(1)    收藏  举报