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

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解

《如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别详解》:本文主要介绍如何通过海康威视设备网络SDK进行Java二次开发摄像头车牌识别的相关资料,描述了如何使用海康威视设备网络SD... 目录前言开发流程问题和解决方案dll库加载不到的问题老旧版本sdk不兼容的问题关键实现流程总结前言作为

SQL 中多表查询的常见连接方式详解

《SQL中多表查询的常见连接方式详解》本文介绍SQL中多表查询的常见连接方式,包括内连接(INNERJOIN)、左连接(LEFTJOIN)、右连接(RIGHTJOIN)、全外连接(FULLOUTER... 目录一、连接类型图表(ASCII 形式)二、前置代码(创建示例表)三、连接方式代码示例1. 内连接(I

Go路由注册方法详解

《Go路由注册方法详解》Go语言中,http.NewServeMux()和http.HandleFunc()是两种不同的路由注册方式,前者创建独立的ServeMux实例,适合模块化和分层路由,灵活性高... 目录Go路由注册方法1. 路由注册的方式2. 路由器的独立性3. 灵活性4. 启动服务器的方式5.

Java中八大包装类举例详解(通俗易懂)

《Java中八大包装类举例详解(通俗易懂)》:本文主要介绍Java中的包装类,包括它们的作用、特点、用途以及如何进行装箱和拆箱,包装类还提供了许多实用方法,如转换、获取基本类型值、比较和类型检测,... 目录一、包装类(Wrapper Class)1、简要介绍2、包装类特点3、包装类用途二、装箱和拆箱1、装