上篇对于UICollectionView默认选中cell采取的是每个cell分别对应一个标识,也就代表着废除了UICollectionView的重用机制。对于较少的数据情况是可以的,但是对于数据比较大,就会造成性能问题。

于是思考在UICollectionView重用机制下,设置默认选中的cell,大致思路就是在cell被选中的时候设置一个selectIndexPath记录下来,在cell被取消选中的时候也用DeselectIndexPath记录下来,除了在cell被选中和取消选中的时候处理,还要在cell被赋值数据和cell即将出现的时候设置。

在为CollectionView设置完数据之后,设置第0个cell被选中:

#pragma mark 设置collectionView的数据
- (void)setupCollectionViewData { for (int i = ; i < ; i++) {
[self.dataArrayM addObject:[NSString stringWithFormat:@"第%d个cell",i]];
} [self.testCollectionView reloadData]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow: inSection:]; [self.testCollectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self collectionView:self.testCollectionView didSelectItemAtIndexPath:indexPath];
}

在viewDidLoad中为seleceIndex设置初试值,并在collectionView选中的方法中,赋值:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.selectIndexPath = [NSIndexPath indexPathForRow: inSection:]; [self setupUICollectionView]; // 设置collectionView的数据
[self setupCollectionViewData];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    self.selectIndexPath = indexPath;
LBCollectionViewCell *cell = (LBCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
[cell setBackgroundColor:[UIColor greenColor]];
[cell.nameLabel setTextColor:[UIColor redColor]];
}

在collectionView取消选中的代理方法中,为DeselectIndexPath赋值:

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
self.DeselectIndexpath = indexPath;
LBCollectionViewCell *cell = (LBCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
if (cell == nil) { // 如果重用之后拿不到cell,就直接返回
return;
}
[cell setBackgroundColor:[UIColor grayColor]];
[cell.nameLabel setTextColor:[UIColor blackColor]];
}

在cell赋值的数据源方法中,设置cell的选中的样式:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
LBCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
[cell.nameLabel setText:self.dataArrayM[indexPath.row]]; if ([self.selectIndexPath isEqual:indexPath]) {
[cell setBackgroundColor:[UIColor greenColor]];
[cell.nameLabel setTextColor:[UIColor redColor]];
} else {
[cell setBackgroundColor:[UIColor grayColor]];
[cell.nameLabel setTextColor:[UIColor blackColor]];
} return cell;
}

在cell出现正在展示的代理方法中再设置选中和未选中的样式:

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
LBCollectionViewCell *LBcell = (LBCollectionViewCell *)cell;
if (self.DeselectIndexpath && [self.DeselectIndexpath isEqual:indexPath]) { [LBcell setBackgroundColor:[UIColor grayColor]];
[LBcell.nameLabel setTextColor:[UIColor blackColor]];
} if ([self.selectIndexPath isEqual:indexPath]) {
[LBcell setBackgroundColor:[UIColor greenColor]];
[LBcell.nameLabel setTextColor:[UIColor redColor]];
}
}

完整代码如下:

//
// ViewController.m
// testSelect
//
// Created by 李江波 on 2019/4/22.
// Copyright © 2019年 jinxiaofu. All rights reserved.
// #import "ViewController.h"
#import "LBCollectionViewCell.h" static NSString *const cellId = @"cellId";
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
// 数据数组
@property (nonatomic, strong) NSMutableArray *dataArrayM; @property (nonatomic, weak) UICollectionView *testCollectionView; // 选中cell的indexPath
@property (nonatomic, strong) NSIndexPath *selectIndexPath; // 取消选中的cell,防止由于重用,在取消选中的代理方法中没有设置
@property (nonatomic, strong) NSIndexPath *DeselectIndexpath;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.selectIndexPath = [NSIndexPath indexPathForRow: inSection:]; [self setupUICollectionView]; // 设置collectionView的数据
[self setupCollectionViewData];
} #pragma mark - private Method
#pragma mark 设置collectionView的数据
- (void)setupCollectionViewData { for (int i = ; i < ; i++) {
[self.dataArrayM addObject:[NSString stringWithFormat:@"第%d个cell",i]];
} [self.testCollectionView reloadData]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow: inSection:]; [self.testCollectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
[self collectionView:self.testCollectionView didSelectItemAtIndexPath:indexPath];
} #pragma mark - setupUI
#pragma mark setupUICollectionView
- (void)setupUICollectionView {
// 设置uicollectionView样式
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.minimumLineSpacing = ;
flowLayout.minimumInteritemSpacing = ;
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; UICollectionView *testCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
[testCollectionView registerClass:[LBCollectionViewCell class] forCellWithReuseIdentifier:cellId];
testCollectionView.delegate = self;
testCollectionView.dataSource = self;
[testCollectionView setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:testCollectionView];
self.testCollectionView = testCollectionView;
} #pragma mark - UICollectionViewDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return ;
} - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [self.dataArrayM count];
} - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
LBCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
[cell.nameLabel setText:self.dataArrayM[indexPath.row]]; if ([self.selectIndexPath isEqual:indexPath]) {
[cell setBackgroundColor:[UIColor greenColor]];
[cell.nameLabel setTextColor:[UIColor redColor]];
} else {
[cell setBackgroundColor:[UIColor grayColor]];
[cell.nameLabel setTextColor:[UIColor blackColor]];
} return cell;
} #pragma mark - UICollectionViewDelegate
- (CGSize) collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(, );
} - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { self.selectIndexPath = indexPath;
LBCollectionViewCell *cell = (LBCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
[cell setBackgroundColor:[UIColor greenColor]];
[cell.nameLabel setTextColor:[UIColor redColor]];
} - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
self.DeselectIndexpath = indexPath;
LBCollectionViewCell *cell = (LBCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
if (cell == nil) { // 如果重用之后拿不到cell,就直接返回
return;
}
[cell setBackgroundColor:[UIColor grayColor]];
[cell.nameLabel setTextColor:[UIColor blackColor]];
} - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
LBCollectionViewCell *LBcell = (LBCollectionViewCell *)cell;
if (self.DeselectIndexpath && [self.DeselectIndexpath isEqual:indexPath]) { [LBcell setBackgroundColor:[UIColor grayColor]];
[LBcell.nameLabel setTextColor:[UIColor blackColor]];
} if ([self.selectIndexPath isEqual:indexPath]) {
[LBcell setBackgroundColor:[UIColor greenColor]];
[LBcell.nameLabel setTextColor:[UIColor redColor]];
}
} #pragma mark - 懒加载
- (NSMutableArray *)dataArrayM {
if (!_dataArrayM) {
_dataArrayM = [NSMutableArray array];
}
return _dataArrayM;
} @end

github地址: https://github.com/OLeGeB/selectCollectionViewCell.git

UICollectionView设置首个cell默认选中(二)的更多相关文章

  1. UICollectionView设置首个cell默认选中

    设置UICollectionView中某个cell的默认选中,刚开始为追求性能,采用同一个cellId去标识UICollectionViewCell,却由于cell的重用会导致之前选中的cell在被重 ...

  2. 【坑】tableView cell默认选中

    在tableView展示的过程时候,如果想一开始就有一些cell默认被选中,不能在cellForRowAtIndexPath中cell.selected=YES, 必须在willDisplayCell ...

  3. 用jQuery的attr()设置option默认选中无效的解决 attr设置属性失效

    表单下拉选项使用selected设置,发现第一次默认选中成功,在页面不刷新的情况下,再次下拉,selected属性设置了,默认选中不生效 在手机端有些浏览器用jQuery的attr()方法设置sele ...

  4. 关于在layui中的table checkbox 默认选中设置

    一.layui版本 layui-v2.4.5 二.设置table的checkbox默认选中 总共有两种方法: 方法1:在返回的json中设置LAY_CHECKED为true,页面上的checkbox就 ...

  5. iOS设置UITableView中Cell被默认选中后怎么触发didselect事件

    //默认选中某个cell [self.searchResultTV selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] a ...

  6. vue中select设置默认选中

    vue中select设置默认选中 一.总结 一句话总结: 通过v-model来:select上v-model的值为option默认选中的那项的值(value) 二.select设置默认选中实例 < ...

  7. HTML中的<select>标签如何设置默认选中的选项

    方法有两种. 第一种通过<select>的属性来设置选中项,此方法可以在动态语言如php在后台根据需要控制输出结果. 1 2 3 4 5 < select  id =  " ...

  8. struts2设置<s:select>默认选中项的方法

    struts2的select标签中,常用的有以下几个属性:(1)struts2中的select 标签中,必须设置的属性只有一个,即是list.(2)select标签的list中必须有值,不然会报错.如 ...

  9. Android RadioGroup中设置默认选中RadioButton 后,选中两个的问题 解决方法

    项目中遇到多个RadioGroup中单选RadioButton ,设置了默认选中第一个 . 然后就 能选中两个RadioButton . . .. 我开始这样给设置默认选中一个的: for (int ...

随机推荐

  1. canvas 实现弹跳效果

    一:创建画布 <canvas width="600" height="600" id="canvas"></canvas& ...

  2. 【转】如何用Redis做LRU-Cache

    LRU(Least Recently Used)最近最少使用算法是众多置换算法中的一种. Redis中有一个maxmemory概念,主要是为了将使用的内存限定在一个固定的大小.Redis用到的LRU ...

  3. com/mysql/jdbc/Driver : Unsupported major.minor version 52.0

    解决方案: 1.jdk7+老版5.0驱动com/mysql/jdbc/Driver 2.jdk8+新版6.0驱动com/mysql/cj/jdbc/Driver

  4. [zhuan]SQLServer查询最近一天,三天,一周,一月,一季度方法

    三天 select * from T_news where datediff(day,addtime,getdate())<= 2 and datediff(day,addtime,getdat ...

  5. CEdit控件[转]

    1.CButton.CEdit等从CWnd继承了重要的功能: 使用CWnd::SetWindowText和CWnd::GetWindowText可以设置和获得窗口或控件上的文本.CWnd::SetFo ...

  6. Office2013 如何安装Matlab notebook

    Office2013 如何安装Matlab notebook 听语音 浏览:912 | 更新:2014-09-16 07:02 1 2 3 4 5 6 7 分步阅读 Office2013(64bit) ...

  7. Python-类-dict

    class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dic ...

  8. Andrew机器学习第一课

    批梯度下降算法:      训练样本为一个时:更新Θi 让代价函数最小,利用沿梯度下降方向函数会变得越来越小.这个函数是代价函数J关于(Θi )的.这里并没有在讨论x,y. 关于为什么式子(图是复制的 ...

  9. 通过Windows API实现的MDI简易程序

    ## #include <windows.h> #include <tchar.h> HINSTANCE hInst; ATOM WindowRegister(WNDPROC ...

  10. How to resolve "your security settings have blocked an untrusted application from running" in Mac

    If you encounter the error "your security settings have blocked an untrusted application from r ...