上篇对于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. Mysql #1406 Data too long 错误

    Mysql #1406 Data too long 错误 http://blog.sina.com.cn/s/blog_68004f680100kgfh.html B. Mysql配置文件:   “在 ...

  2. python模块:pickle

    """Create portable serialized representations of Python objects. See module copyreg f ...

  3. ext中对json数据的处理解析

    看贴:http://blog.csdn.net/xieshengjun2009/article/details/5959687

  4. Mybatis-Plus 实战完整学习笔记(三)------导入MybatisPlus环境

    1.dao层接口引入 package com.baidu.www.mplus.mapper; import com.baidu.www.mplus.bean.Employee; import com. ...

  5. mysql学习之路_乱码问题

    中文数据问题: 中文数据问题本质就说字符集问题, 计算机只识别二进制,人类识别符号:需要友谊个二进制与字符对应关系(字符集). 报错:服务器没有识别对应的四个字节. 服务器认为的数据是utf—8,一个 ...

  6. BZOJ 2301 [HAOI2011]Problem b (分块 + 莫比乌斯反演)

    2301: [HAOI2011]Problem b Time Limit: 50 Sec  Memory Limit: 256 MBSubmit: 6519  Solved: 3026[Submit] ...

  7. 通过sftp操作Linux服务器上的文件(java)

    本文为实现对linux服务器文件的操作.windows服务器不支持. 引入jar包:jsch-0.1.42.jar package com.csvreader.sftp; import java.io ...

  8. ArcGIS API for Silverlight/ 开发入门 环境搭建

    Silverlight/ 开发入门 环境搭建1 Silverlight SDK下载ArcGIS API for Microsoft Silverlight/WPF ,需要注册一个ESRI Gloab ...

  9. C++的重载流输出运算符

    // 下列代码输出什么?#include <iostream>#include <string>// typedef basic_ostream<char> ost ...

  10. java基础-day24

    第01天 java基础加强 今日内容介绍 u Junit单元测试及反射概述 u 反射操作构造方法.成员方法.成员属性 u properties的基本操作 u 综合案例 第1章   Junit单元测试及 ...