解决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;}
修改之后的效果图如下所示