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];
}
相关推荐
帅次7 小时前
Android 17 开发者实战:核心更新与应用场景落地指南
android·java·ios·android studio·iphone·android jetpack·webview
人月神话Lee8 小时前
【图像处理】Core Image 与 GPU 渲染管线——让滤镜飞起来
ios·ai编程·图像识别
帅次15 小时前
讯飞与腾讯云:Android 实时语音识别服务对比选择
android·ios·微信小程序·小程序·android studio·android runtime
择势17 小时前
用一套View代码,同时支持RTL和LTR布局混合排版
ios
游戏开发爱好者818 小时前
iOS开发工具推荐:Xcode、AppCode、SwiftLint使用心得与效率提升
ide·vscode·macos·ios·个人开发·xcode·敏捷流程
2501_9159090618 小时前
深入理解HTTPS中间人抓包技术原理与实战指南
网络协议·http·ios·小程序·https·uni-app·iphone
择势1 天前
基于声网 Agora RTM + RTC SDK 实现 iOS 语音聊天室 —— 常见问题汇总 & 解决方案手册
ios
择势1 天前
基于声网 Agora RTM + RTC SDK 实现 iOS 语音聊天室(进阶封装)
ios
择势1 天前
基于声网 Agora RTM + RTC SDK 实现 iOS 语音聊天室——从零到可跑的指南
ios
白玉cfc1 天前
【iOS】底层原理:类的加载
ios·objective-c·xcode