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];
}
相关推荐
kymjs张涛6 小时前
零一开源|前沿技术周刊 #12
ios·google·github
2501_9159184117 小时前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
笔沫拾光17 小时前
iOS 正式包签名指南
flutter·ios·ios签名
Magnetic_h1 天前
【iOS】锁的原理
笔记·学习·macos·ios·objective-c·cocoa·xcode
Digitally1 天前
将 iPhone 联系人转移到 Infinix 的完整指南
ios·cocoa·iphone
imLix2 天前
RunLoop 实现原理
前端·ios
归辞...2 天前
「iOS」————设计架构
ios·架构
i紸定i2 天前
解决html-to-image在 ios 上dom里面的图片不显示出来
前端·ios·vue·html·html-to-image
YungFan3 天前
iOS26适配指南之UIButton
ios·swift
红橙Darren3 天前
手写操作系统 - 编译链接与运行
android·ios·客户端