UICollectionView 实现整页翻动(每页3个cell)

news2024/10/6 4:11:22

提示:页面架构是通过UICollectionView做的分页,分页点PageControl使用的是<SDCycleScrollView/TAPageControl.h> ,布局架构使用的是Masonry


前言

为了实现UICollectionView无限翻动,连续滑动,主要是利用pagingEnabled属性,配合 UIScrollViewDelegate的代理方法来实现的。


一、准备列表数据和计算思路

1.数据源的创建(9个元素,作为数据源),目的是让翻页效果是3页。

最终达到效果:

2. 思路:通过设置轮播倍数目的是通过建立多个section来实现轮播联动在最后一次循环从头开始排序达到循环播放。

二、使用步骤

1.初始化尺寸数据准备

代码如下(示例):

static CGFloat const Cell_Height = 174;
static CGFloat const PageDot_Height = 30;

// 轮播倍数Num
static const int kLoopMaxMultiple = 4;
-(void)setArr_data:(NSMutableArray *)arr_data{
    _arr_data = arr_data;
    self.pageControl.numberOfPages = arr_data.count%3==0?arr_data.count/3:(arr_data.count/3+1);
    self.pageControl.currentPage = 0;
    [self.mainCV reloadData];
}

2.绘画view

代码如下(示例):

- (void)drawView {
    self.backgroundColor = [UIColor clearColor];
    CGFloat img_w = (SCREEN_WIDTH - 15 * 4) / 3.0;

    [self addSubview:self.bkgView];
    self.bkgView.backgroundColor = [UIColor clearColor];
    [self.bkgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self);
        make.height.mas_equalTo(Cell_Height+PageDot_Height);
    }];

    //collectionview
    [self.bkgView addSubview:self.mainCV];
    self.mainCV.delegate = self;
    self.mainCV.dataSource = self;
    [self.mainCV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bkgView.mas_top);
        make.left.mas_equalTo(self.bkgView.mas_left).mas_offset(15);
        make.right.mas_equalTo(self.bkgView.mas_right).mas_offset(-0);
        make.height.mas_equalTo(Cell_Height);
    }];

    [self.mainCV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.mainCV registerClass:[TZUploadNewPriceGoodsColCell class] forCellWithReuseIdentifier:@"TZUploadNewPriceGoodsColCell"];

    //pagecontrol
    [self.bkgView addSubview:self.pageControl];
    self.pageControl.frame = CGRectMake(0, Cell_Height, SCREEN_WIDTH, 30);
}


- (UIImage *)zd_imageWithColor:(UIColor *)color
                          size:(CGSize)size
                          text:(NSString *)text
                textAttributes:(NSDictionary *)textAttributes
                      circular:(BOOL)isCircular {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    // circular
    if (isCircular) {
        CGPathRef path = CGPathCreateWithEllipseInRect(rect, NULL);
        CGContextAddPath(context, path);
        CGContextClip(context);
        CGPathRelease(path);
    }
    // color
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    //    // text
    //    CGSize textSize = [text sizeWithAttributes:textAttributes];
    //    [text drawInRect:CGRectMake((size.width - textSize.width) / 2, (size.height - textSize.height) / 2, textSize.width, textSize.height) withAttributes:textAttributes];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark - get -
-(UIView *)bkgView{
    if(!_bkgView){
        _bkgView = [[UIView alloc]init];
        _bkgView.backgroundColor = [UIColor clearColor];
        _bkgView.userInteractionEnabled = YES;
    }
    return _bkgView;
}

-(UICollectionView *)mainCV{
    if(!_mainCV){
        CGFloat img_w = (SCREEN_WIDTH - 15 * 4) / 3.0;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(img_w, img_w*2);

        //管上下缝隙 minimumLineSpacing
        flowLayout.minimumLineSpacing = 15;
        //管左右缝隙 minimumInteritemSpacing
        flowLayout.minimumInteritemSpacing = 15;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 0);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _mainCV = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _mainCV.bounces = YES;
        _mainCV.pagingEnabled = YES;
        _mainCV.backgroundColor = [UIColor clearColor];
        _mainCV.showsHorizontalScrollIndicator = NO;
        _mainCV.showsVerticalScrollIndicator = NO;
    }
    return _mainCV;
}

- (TAPageControl *)pageControl {
    if (_pageControl == nil) {
        _pageControl = [[TAPageControl alloc] init];
        _pageControl.currentDotImage = [self zd_imageWithColor:[UIColor colorWithHexString:@"#C32136"] size:CGSizeMake(5, 5) text:@"" textAttributes:@{} circular:YES];
        _pageControl.dotImage = [self zd_imageWithColor:[UIColor colorWithHexString:@"#DEDEDE" alpha:1.0] size:CGSizeMake(5, 5) text:@"" textAttributes:@{} circular:YES];
        _pageControl.shouldResizeFromCenter = YES;
    }
    return _pageControl;
}

3.关键步骤和思路

1.获取显示页面cell的index目的是为了计算页面的页数

/**
 获取scrollView的index
 
 @param scrollView scrollView
 @return index
 */
- (NSIndexPath* )indexWithScrollView:(UIScrollView * _Nonnull)scrollView {

    UICollectionView *cv = scrollView;
    NSArray* visibleCellIndex = cv.indexPathsForVisibleItems;
     NSArray *sortedIndexPaths = [visibleCellIndex sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSIndexPath *path1 = (NSIndexPath *)obj1;
            NSIndexPath *path2 = (NSIndexPath *)obj2;
            return [path1 compare:path2];
        }];

    NSIndexPath* indexPath = [sortedIndexPaths firstObject];
    return indexPath;
}

2.滚动到相应的页数collectionview和Pagecontrol联动

/**
 滚动到指定索引

 @param scrollView scrollView
 */
- (void)scrollToIndex:(UIScrollView *)scrollView {
    NSIndexPath* index = [self indexWithScrollView:scrollView];

    NSInteger item_section = index.section;
    if (index.section == kLoopMaxMultiple - 1) {
        item_section = 0;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem: index.row inSection:item_section];
    [self.mainCV scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    self.pageControl.currentPage = index.row/3;

}

3.UICollectionView代理方法(将分格空间做在cell 里面,不然整页翻动会有偏移偏移的量为分隔空间的倍数),将数据赋值多份通过多个section来实现第一次最后一帧能够与第一帧接上

#pragma mark-- 数据 --

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return kLoopMaxMultiple;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.arr_data.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    TZUploadNewPriceGoodsColCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TZUploadNewPriceGoodsColCell" forIndexPath:indexPath];
    
    cell.titL.text = [NSString stringWithFormat:@"题目:第%ld页 -- row:%ld  -- section:%ld",indexPath.row/3+1,indexPath.row,indexPath.section];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat img_w = (SCREEN_WIDTH - 15 * 4) / 3.0;

    return CGSizeMake(floor(img_w)+15, Cell_Height);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.000001;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.000001;
}

// 设置区头尺寸高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGSize size = CGSizeMake(0.00001, 0.00001);
    return size;
}

// 设置区尾尺寸高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeMake(0.00001, 0.00001);
}

 4.UIScrollViewDelegate代理方法

  1. scrollViewDidEndScrollingAnimation 不是人为滚动的方法

  2. scrollViewDidEndDecelerating 是人为滑动的方法

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSIndexPath *indexP = [self indexWithScrollView:scrollView];
    NSInteger index = indexP.row/3;
    self.pageControl.currentPage = index;
}

//不是人为滚动
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self scrollToIndex:scrollView];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
}
//是人为滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollToIndex:scrollView];
}


总结

  1. 通过UICollectionView的属性@property (nonatomic, readonly) NSArray<NSIndexPath *> *indexPathsForVisibleItems;来获取当前页面上显示的cell再排序(**排序很重要)

  2. 当当前cell的index.section == kLoopMaxMultiple - 1 是最后一个分区的时候一定要去滚动到第一个分区从新开始     [self.mainCV scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO]; (动画要关了)

  3. UIScrollViewDelegate的代理一定要区分停止滚动的类型(人为拖拽scrollViewDidEndDecelerating、和代码自动滚动scrollViewDidEndScrollingAnimation

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/494771.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

海豚1.3单节点,多集群设置

最近出差忙项目&#xff0c;一直没更新&#xff0c;现在项目结尾了。回来继续搞集群 公司因为CDH升级为CDP&#xff0c;两套环境数据和任务慢慢迁移&#xff0c;但是调度任务需要同时跑批。 而我们的海豚调度是单节点的&#xff0c;master和worker等服务都在一台节点上。 之前…

基于VBA实现成绩排序的最佳方法-解放老师的双手

作为一名老师&#xff0c;每到期末就要面对一件让人头疼的事情——成绩表统计。 首先&#xff0c;要收集每个学生的考试成绩。这需要花费大量的时间和精力&#xff0c;因为每个学生都有多门科目的成绩需要统计。 其次&#xff0c;要将每个学生的成绩录入到电子表格中。这看起来…

【今天聊聊生产力】提升研发生产力的神器推荐

1、Free Mybatis Tool、MybatisX 用于DAO层和Mapper层之间跳转 Mapper和DAO层跳转&#xff0c;可以用的插件比较多&#xff0c;比较推荐如下两款&#xff0c;功能基本一致&#xff0c;只是样式小有差别。 Free Mybatis Tool&#xff0c;样式为一个绿色箭头&#xff0c;简洁明了…

docker 部署JAVA应用OOM的排障经历——筑梦之路

故障现象&#xff1a; 使用docker部署JAVA的应用&#xff0c;tomcat作为中间件容器&#xff0c;启动应用时总是报错无法创建Java虚拟机&#xff0c;然后就是OOM 报错信息&#xff1a; 不管是从docker容器的日志还是系统日志均未发现有用的信息&#xff0c;也尝试更换过镜像tom…

C++入门3(C++新特性 using string auto)

C入门3 C新特性auto推导规则auto 作为函数的形参类型decltype基于范围for循环 typedef与usingC语言定义变量typedef 在C语言中的写法using在C11中的写法using与template的结合 string的简单使用 C新特性 auto推导规则 auto类型推导: auto定义的变量&#xff0c;可以根据初始化…

开源推荐,超级棒的云原生的Kafka管控平台,清新优雅~~

哈喽&#xff0c;大家好&#xff0c; 之前给大家介绍过很多优秀的后台管理系统&#xff0c;但是都感觉还少&#xff0c;今天再来推荐一个。 最近新接触到一个项目&#xff0c;确实把我惊艳到了&#xff0c;太适合使用了&#xff0c;极大地方便了用户和运维人员的日常使用&…

(三)Kubernetes - 手动部署(二进制方式安装)

Kubernetes - 手动部署 [ 2 ] 1 部署主节点1.1 生成kube-apiserver证书1.1.1 自签证书颁发机构(CA)1.1.2 使用自签CA签发kube-apiserver https证书 1.2 下载k8s-server1.3 解压二进制包1.4 部署kube-apiserver1.4.1 创建配置文件1.4.2 拷贝刚才生成的证书1.4.3 启用TLS bootstr…

部署PHP开源项目SuiteCRM

部署PHP开源项目SuiteCRM 前言部署PHP项目创建站点上传PHP源码安装依赖 SuiteCRM安装安装向导中文语言修改数据库密码 前言 因人力资源部想要开发一套适用于他们方便管理的系统&#xff0c;但无整体构思&#xff0c;在网络中找到了开源企业管理软件SuiteCRM&#xff0c;想要作为…

基于SSM框架疫情之下社区管理系统(spring+springmvc+mybatis+jsp+jquery+bootstrap)

一、项目简介 本项目是一套基于SSM框架疫情之下社区管理系统&#xff0c;主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者。 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff0c…

Java8新特性—Lambda表达式

Java 8是Java编程语言的一个版本&#xff0c;于2014年发布。它引入了许多新的特性和改进。 Lambda表达式是Java 8中引入的一个重要的新特性&#xff0c;它提供了一种更加简洁、灵活的方式来编写函数式接口的实现&#xff0c;从而提高了代码的可读性和简洁性。 在本文中&#…

什么是FPGA?关于FPGA基础知识 一起来了解FPGA lattice 深力科 MachXO3系列 LCMXO3LF-9400C-5BG256C

什么是FPGA&#xff1f;关于FPGA基础知识 一起来了解FPGA lattice 深力科 MachXO3系列 LCMXO3LF-9400C-5BG256C FPGA基础知识&#xff1a;FPGA是英文Field&#xff0d;Programmable Gate Array的缩写&#xff0c;即现场可编程门阵列&#xff0c;它是在PAL、GAL、CPLD等可编程器…

golang web学习随便记2

在前一篇中&#xff0c;我们直接在 index 这个 handler func 中解析了模板&#xff0c;定义了数据&#xff0c;然后执行模板显示“拼合”了数据的网页。这是一个客户被动看的页面。实际的应用显然需要能够处理用户的请求。对于浏览器客户端的请求&#xff0c;我们先要来了解和请…

pytorch——损失函数之nn.BCELoss二进制交叉熵和 nn.BCEWithLogitsLoss

文章目录 1、pytorch损失函数之nn.BCELoss()&#xff08;二进制交叉熵)1.1 是什么&#xff1f;1.2 怎么代码实现和代码使用&#xff1f;1.3 推导过程分析交叉熵作为损失函数的梯度情况&#xff1a;举一个sigmoid导致的梯度消失的MSE损失的例子 1.3 应用场景1.3.1 二分类1.3.2 多…

java版工程项目管理系统平台,助力工程企业实现数字化管理系统源代码

Java版工程项目管理系统 Spring CloudSpring BootMybatisVueElementUI前后端分离 功能清单如下&#xff1a; 首页 工作台&#xff1a;待办工作、消息通知、预警信息&#xff0c;点击可进入相应的列表 项目进度图表&#xff1a;选择&#xff08;总体或单个&#xff09;项目显示1…

一文讲透TCP/IP协议 | 图解+秒懂+史上最全

目录 &#x1f64b;‍♂️ TCP/IP协议详解 &#x1f64b;‍♂️ TCP/IP协议的分层模型 OSI模型的七层框架 TCP/IP协议与七层ISO模型的对应关系 &#xff08;一&#xff09;TCP/IP协议的应用层 &#xff08;二&#xff09;TCP/IP协议的传输层 &#xff08;三&#xff09;…

Vuex从了解到实际运用(二)——获取vuex中的全局状态(state getters)

vuex从了解到实际运用——获取vuex中的全局状态state getters 知识回调&#xff08;不懂就看这儿&#xff01;&#xff09;场景复现项目实战vuex定义一个store实例在store中定义数据在组件中获取值vuex的计算属性通过getters获取全局状态state和getters获取全局状态的区别 知识…

Windows安装Docker 容器教程

Windows安装Docker 容器教程 什么是docker I. 简介 什么是 Docker 容器 Docker 容器是一种轻量级、可移植、自包含的软件打包和部署技术。它可以将应用程序和依赖项打包在一个可移植的容器中&#xff0c;并提供一个一致的运行环境&#xff0c;无论在哪个计算机上运行都能够…

Copyleaks:AI抄袭和内容检测工具

【产品介绍】 Copyleaks是一个基于AI人工智能的抄袭和内容检测工具&#xff0c;可以帮助用户在互联网上发现和防止内容被盗用。支持检测各种类型的文本&#xff0c;包括学术论文、网站内容、商业文件、法律合同、创意作品等&#xff0c;并提供详细的相似度报告和原始来源链接。…

基于R语言APSIM模型应用

随着数字农业和智慧农业的发展&#xff0c;基于过程的农业生产系统模型在模拟作物对气候变化的响应与适应、农田管理优化、作物品种和株型筛选、农田固碳和温室气体排放等领域扮演着越来越重要的作用。APSIM (Agricultural Production Systems sIMulator)模型是世界知名的作物生…

【Hello Network】TCP协议

作者&#xff1a;小萌新 专栏&#xff1a;网络 作者简介&#xff1a;大二学生 希望能和大家一起进步 本篇博客简介&#xff1a;较为详细的介绍TCP协议 TCP协议 TCP协议可靠性TCP的协议格式序号与确认序号窗口大小六个标志位 确认应答机制 &#xff08;ACK&#xff09;超时重传机…