UICollectionView详解二:UICollectionViewFlowLayout

2023-12-21 12:58

本文主要是介绍UICollectionView详解二:UICollectionViewFlowLayout,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本人录制技术视频地址:https://edu.csdn.net/lecturer/1899 欢迎观看。

UICollectionViewFlowLayout是一个具体的layout对象,用来把item布局在网格中,并且可选页眉和页脚。在collection view中的items,可以从一行或者一列flow至下一行或者下一列(行或者列取决于滚动的方向)。每行都会根据情况,包含尽可能多的Cells。Cells可以是相同的尺寸,也可以是不同的尺寸。

页眉页脚的属性如下图


当垂直的时候,需要设置Height,如下图


 当水平的时候,需要设置Width,如下图


Section Inset : 我们先通过两个图来看看Sections Insets是怎么回事


 


 从上面的两个图中,我们大概知道了,Section Inset就是某个section中cell的边界范围。

本节中得Demo,就是针对一行进行设计的。效果图如下:



一行显示很多的Icon,并且距中心点越近的Icon,尺寸越大;距离中心点越远的Icon,尺寸逐渐变小。而且在滚动过程中,也是这种效果。

1. 主界面的代码如下(如有不明白的,请参考我上一节讲解的内容,请点击这里):

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic,strong) NSMutableArray *images;
@property (nonatomic,weak) UICollectionView *collectionView;
@endstatic NSString *const identifer = @"ImageCell";@implementation ViewController-(NSMutableArray *)images {if (!_images) {_images = [NSMutableArray array];for (int i=1;i<=20;i++) {[_images addObject:[NSString stringWithFormat:@"%d.jpg",i]];}}return _images;
}- (void)viewDidLoad {[super viewDidLoad];CGRect rect = CGRectMake(0, 250, self.view.frame.size.width,200);UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:rect collectionViewLayout:[[LFFlowLayout alloc] init]];collectionView.dataSource = self;collectionView.delegate = self;// 注册collectionView(因为是从xib中加载cell的,所以registerNib)[collectionView registerNib:[UINib nibWithNibName:@"ImageCell" bundle:nil] forCellWithReuseIdentifier:identifer];[self.view addSubview:collectionView];self.collectionView = collectionView;
}#pragma mark - 点击屏幕空白处,切换布局模式
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//    if ([self.collectionView.collectionViewLayout isKindOfClass:[LFFlowLayout class]]) {
//        [self.collectionView setCollectionViewLayout:[[LFNormalLayout alloc] init] animated:YES];
//    }
//    else{
//        [self.collectionView setCollectionViewLayout:[[LFFlowLayout alloc] init] animated:YES];
//    }
//
//}#pragma mark - delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {return  self.images.count;
}- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifer forIndexPath:indexPath];cell.iconName = self.images[indexPath.item];return cell;
}- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {// 1. 删除模型数据[self.images removeObjectAtIndex:indexPath.item];// 2. 删除UI元素[collectionView deleteItemsAtIndexPaths:@[indexPath]];
}

2. 自定义一个类,继承自UICollectionViewFlowLayout

@interface LFFlowLayout : UICollectionViewFlowLayout@end

3. 控制布局的主要代码如下,有以下几点,我进行说明:

1) prepareLayout 方法可以对布局中得内容进行初始化工作。如果init方法中执行的代码不起作用,可以放在prepareLayout中。

- (void)prepareLayout {[super prepareLayout];...
}
2)   允许CollectionView Bounds发生变化时,重新进行布局, 要实现下面的方法

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {return YES;
}

3) 流式处理中最关键的方法如下,用来获取CollectionView的所有Item项的layout,进行相印的处理。

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {...
}
4) 对于Item的细节计算,可以调用下面的方法,完成定位处理。

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {...
}


完整的实现代码如下:

#define kItemWidth 100#import "LFFlowLayout.h"@implementation LFFlowLayout-(instancetype)init
{if(self=[super init]){}return self;
}- (void)prepareLayout {[super prepareLayout];// 设置为水平滚动self.scrollDirection = UICollectionViewScrollDirectionHorizontal;// 设置每个Item之间的距离self.minimumLineSpacing = 100;// 重新设置Item的尺寸,不然的话,有等比例缩小的可能self.itemSize = CGSizeMake(kItemWidth, kItemWidth);
}#pragma mark - 重写父类的方法
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {return YES;
}// 获取CollectionView的所有Item项,进行相印的处理(移动过程中,控制各个Item的缩放比例)
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {NSArray *array = [super layoutAttributesForElementsInRect:rect];CGFloat inset = (self.collectionView.frame.size.width - kItemWidth) * 0.5;// 设置第一个和最后一个默认居中显示self.collectionView.contentInset = UIEdgeInsetsMake(0, inset, 0, inset);CGRect visibleRect;visibleRect.origin =self.collectionView.contentOffset;visibleRect.size = self.collectionView.frame.size;CGFloat collectionViewCenterX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;for (UICollectionViewLayoutAttributes *attrs in array) {// 只处理正在界面上面显示的Itemif(!CGRectIntersectsRect(visibleRect, attrs.frame)) continue;// 计算各个Item的缩放比例(距离中线越近,缩放比例就越大)CGFloat scale;// 防止突变的情况(当Item的中心与collectionView中心的距离大于等于collectionView宽度的一半时,Item不缩放,平稳过度)if(ABS(attrs.center.x - collectionViewCenterX) >= self.collectionView.frame.size.width * 0.5){scale = 1;}else{scale = 1 + 0.8 * (1 - ABS(attrs.center.x - collectionViewCenterX) / (self.collectionView.frame.size.width * 0.5));}attrs.transform3D = CATransform3DMakeScale(scale, scale, 1);}return array;
}// 当UICollectionView停止的那一刻ContentOffset的值(控制UICollectionView停止时,有一个Item一定居中显示)
// 1.proposedContentOffset默认的ContentOffset
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {//1. 获取UICollectionView停止的时候的可视范围CGRect contentFrame;contentFrame.size = self.collectionView.frame.size;contentFrame.origin = proposedContentOffset;NSArray *array = [self layoutAttributesForElementsInRect:contentFrame];//2. 计算在可视范围的距离中心线最近的ItemCGFloat minCenterX = CGFLOAT_MAX;CGFloat collectionViewCenterX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;for (UICollectionViewLayoutAttributes *attrs in array) {if(ABS(attrs.center.x - collectionViewCenterX) < ABS(minCenterX)){minCenterX = attrs.center.x - collectionViewCenterX;}}//3. 补回ContentOffset,则正好将Item居中显示return CGPointMake(proposedContentOffset.x + minCenterX, proposedContentOffset.y);
}@end


这篇关于UICollectionView详解二:UICollectionViewFlowLayout的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/520086

相关文章

Linux之计划任务和调度命令at/cron详解

《Linux之计划任务和调度命令at/cron详解》:本文主要介绍Linux之计划任务和调度命令at/cron的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux计划任务和调度命令at/cron一、计划任务二、命令{at}介绍三、命令语法及功能 :at

Java使用SLF4J记录不同级别日志的示例详解

《Java使用SLF4J记录不同级别日志的示例详解》SLF4J是一个简单的日志门面,它允许在运行时选择不同的日志实现,这篇文章主要为大家详细介绍了如何使用SLF4J记录不同级别日志,感兴趣的可以了解下... 目录一、SLF4J简介二、添加依赖三、配置Logback四、记录不同级别的日志五、总结一、SLF4J

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

前端CSS Grid 布局示例详解

《前端CSSGrid布局示例详解》CSSGrid是一种二维布局系统,可以同时控制行和列,相比Flex(一维布局),更适合用在整体页面布局或复杂模块结构中,:本文主要介绍前端CSSGri... 目录css Grid 布局详解(通俗易懂版)一、概述二、基础概念三、创建 Grid 容器四、定义网格行和列五、设置行

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

《Node.js数据库CRUD项目示例详解(完美解决方案)》:本文主要介绍Node.js数据库CRUD项目示例详解(完美解决方案),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考... 目录项目结构1. 初始化项目2. 配置数据库连接 (config/db.js)3. 创建模型 (models/

SQL表间关联查询实例详解

《SQL表间关联查询实例详解》本文主要讲解SQL语句中常用的表间关联查询方式,包括:左连接(leftjoin)、右连接(rightjoin)、全连接(fulljoin)、内连接(innerjoin)、... 目录简介样例准备左外连接右外连接全外连接内连接交叉连接自然连接简介本文主要讲解SQL语句中常用的表

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的