iOS collectionViewCell显示选中颜色

demo

git地址:点这里

原理思想简介
  1. reloadData只会刷新内存中保存的cell,注意cell会复用,所以最多会刷新当前显示的加上一个用来复用的cell。
  2. 实现的思想有两种:
  • 设置一个全局的变量保存选中的位置,然后刷新collectionView,在返回cell的方法中判断是不是选中的cell,然后显示对应的颜色。
  • 在model中设置一个颜色的属性,每次对应的修改model的属性值,然后刷新collectionView就可以实现选中颜色。
主要代码(此处只展示第一种实现方式)
复制代码
 - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
StyleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:itemResuableStr forIndexPath:indexPath];

//判断显示颜色
UIColor *tempColor = (self.selectIndex == indexPath) ? [UIColor redColor] : [UIColor groupTableViewBackgroundColor];
[cell setItemWithDic:self.styleInfoMuArray[indexPath.item] BackColor:tempColor];
return cell;
}

 #pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

//这句是无关的,请忽略
//设置大图
self.originalImage.image = [self.styleInfoMuArray[indexPath.item] objectForKey:StyleImage];

//设置选中位置
self.selectIndex = indexPath;

//刷新collectionView
[self.selectStyleCollectionView reloadData];
}
相关推荐
黑科技iOS上架10 小时前
App Store5.6隐藏功能究竟怎么排查?
ios·审核
Yannik13 小时前
iOS Swift Package Manager(SPM)私有组件完整实操
ios·swift
随遇丿而安13 小时前
第 4 周:28KB 的 PNG 占了 8MB 内存,因为图片内存看尺寸不看文件大小
ios
leizhen1984080914 小时前
Vibe Coding:门槛降了,但判断力成了新的门槛
人工智能·安全·ios
我就是不信18 小时前
Swift 方法派发机制详解
开发语言·ios·swift
AIsoft_868920 小时前
科会通录音工具倍速回放怎么切换速度
ios·智能手机
老李IT笔记21 小时前
设备显示在线但指令没回执:三类静默失效的排查顺序
ios·iphone
芯械研究所21 小时前
她宁、益博思、倍思、绿联哪款ipad电容笔好?四款电容笔款式实测解读
ios·ipad·电容笔·电容笔推荐·电容笔测评
Yannik2 天前
iOS CocoaPods私有库完整搭建+踩坑实战总结
ios·cocoapods