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];
}
相关推荐
他们都不看好你,偏偏你最不争气3 小时前
【iOS】push 和 present
ios
2501_916013746 小时前
HTTPS 抓包难点分析,从端口到工具的实战应对
网络协议·http·ios·小程序·https·uni-app·iphone
2501_915918418 小时前
uni-app 项目 iOS 上架效率优化 从工具选择到流程改进的实战经验
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张8 小时前
如何在不同 iOS 设备上测试和上架 uni-app 应用 实战全流程解析
android·ios·小程序·https·uni-app·iphone·webview
wjm0410069 小时前
ios面试八股文
ios·面试
张较瘦_12 小时前
[论文阅读] 人工智能 + 软件工程 | 大模型破局跨平台测试!LLMRR让iOS/安卓/鸿蒙脚本无缝迁移
论文阅读·人工智能·ios
m0_6410310521 小时前
在选择iOS代签服务前,你必须了解的三大安全风险
ios
开开心心loky1 天前
[iOS] push 和 present Controller 的区别
ui·ios·objective-c·cocoa
白玉cfc1 天前
【iOS】push,pop和present,dismiss
macos·ios·cocoa
低调小一1 天前
iOS 开发入门指南-HelloWorld
ios