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];
}
相关推荐
AIsoft_868815 小时前
iOS端录音转文字工具实测:自媒体创作者高效整理指南
ios·媒体
库奇噜啦呼1 天前
【iOS】Core Data
ios
2501_915106322 天前
TraceEagle 代理抓包教程 本机和手机的 HTTPS 抓包方法
网络协议·计算机网络·网络安全·ios·adb·https·udp
云逸_2 天前
Cinder:基于 Swift Macro 与 Mach-O Section 的解耦注册机制
ios·swift
末代iOS程序员华仔2 天前
从 Figma 到上架:使用 Codex 与 MCP 全流程实现 AI 聊天 App
flutter·ios·swift
极客猴子2 天前
苹果手机怎么快速总结长文本?iOS录音APP实测对比
ios·智能手机
一牛2 天前
Swift 循环引用
macos·ios
迷雾悠悠3 天前
企业微信iPad协议聚合聊天系统:从原理到实战开发指南
ios·企业微信·ipad
LDyun_3 天前
.2026主流云手机测评,8款机型高压挂机实测
ios·智能手机·安卓·玩游戏
pop_xiaoli3 天前
【iOS】YYModel源码学习
学习·ios·objective-c·cocoa