UICollectionView 实际使用

news2024/9/21 21:42:07

一. 使用UICollectionView制作书架

我想的书架是那种每一排都可以滑动的。暂时的想法是使用两个collectionView,第一个collectionView布置书架的每一排,第二个布置每一排内部的书。

  1. 布置外部的colletionView,这部分很简单,item的大小就是屏幕的宽和书的高。
- (void) initCollectionView {
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(KSreenWidth, 120);
    layout.minimumLineSpacing = 35;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[BookcaseFaceCell class] forCellWithReuseIdentifier:@"bookcaseFace"];
    
    [self.view addSubview:self.collectionView];
}

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

- (__kindof UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BookcaseFaceCell* cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"bookcaseFace" forIndexPath:indexPath];
    return cell;
}
  1. 自定义cell,这个cell需要使用collectionView布局书架中的每一本书。注意这个collectionView是横向排列的。

cell.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface BookcaseFaceCell : UICollectionViewCell
<
UICollectionViewDelegate,
UICollectionViewDataSource
>

@property (nonatomic, strong) UICollectionView* collectionView;

@end

NS_ASSUME_NONNULL_END

cell.m

#import "BookcaseFaceCell.h"
#import "BookcaseCell.h"

#define KSreenWidth [UIScreen mainScreen].bounds.size.width

@implementation BookcaseFaceCell

- (instancetype) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initCollectionView];
    }
    return self;
}

- (void) initCollectionView {
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((KSreenWidth - 60) / 4, 120);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    [self.collectionView registerClass:[BookcaseCell class] forCellWithReuseIdentifier:@"bookcase"];
    
    [self.contentView addSubview:self.collectionView];
}

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

- (__kindof UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BookcaseCell* cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"bookcase" forIndexPath:indexPath];
    
    if (indexPath.row % 2 == 0) {
        [cell.imageView setImage:[UIImage imageNamed:@"book.jpeg"]];
    } else {
        [cell.imageView setImage:[UIImage imageNamed:@"book2.jpeg"]];
    }
    
    return cell;
}

@end
  1. 展示书面的cell,就是一个普通的展示图片的cell。

cell.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface BookcaseCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView* imageView;

@end

NS_ASSUME_NONNULL_END

cell.m

#import "BookcaseCell.h"

@implementation BookcaseCell

- (instancetype) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
        [self.contentView addSubview:self.imageView];
    }
    return self;
}

@end

结果展示:
在这里插入图片描述

二. 使用CollectionView制作轮播推荐图

我想要的轮播推荐图需要那种图片距离屏幕中心越近,就会越来越大的那种效果。

在这里我们需要自定义我们的layout。

基本思想是将远离中心的图片缩小,以屏幕中心图片的大小做为标准计算布局。

  1. 新建MyLayout类继承自UICollectionViewFlowLayout。
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyLayout : UICollectionViewFlowLayout

@end

NS_ASSUME_NONNULL_END
  1. 重写prepareLayout方法,开启collectionView的刷新。注意计算第一个图片的位置,通过设置collectionView的contenyInset来确保第一张图片位于屏幕中心。
- (void) prepareLayout {
    [super prepareLayout];
    
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    // 计算第一个图片所在的位置
    CGFloat margin = (self.collectionView.frame.size.width - self.itemSize.width) / 2;
    self.collectionView.contentInset = UIEdgeInsetsMake(0, margin, 0, margin);
    
}

// 开启刷新
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}
  1. 重写- (nullable NSArray<__kindof UICollectionViewLayoutAttributes*> *) layoutAttributesForElementsInRect:(CGRect)rect方法。

通过计算每一个item的中心x值(这个值需要减去collectionView的滚动偏移量)与collectionView的中心x值的距离来判断图片距离中心的距离。根据这个距离计算图片的缩小系数。

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes*> *) layoutAttributesForElementsInRect:(CGRect)rect {
    
    // 扩大刷新范围防止闪屏
    rect.size.width += KSreenWidth;
    rect.origin.x -= KSreenWidth / 2;
    
    // 调用父类获取布局
    NSArray* array = [[NSArray alloc] initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:YES];
    
    for (UICollectionViewLayoutAttributes* attributes in array) {
        // 保存图片变化系数
        CGFloat scale = 1.0;
        // collectionView的center.x
        CGFloat centerX = self.collectionView.center.x;
        // 图片距离中心的位置
        CGFloat step = ABS(centerX - (attributes.center.x - self.collectionView.contentOffset.x));
        // 使用cos函数计算一个明显顺滑的变化系数
        scale = fabsf(cosf(step / centerX * M_PI / 5));
        
        attributes.transform = CGAffineTransformMakeScale(scale, scale);
    }
    
    return array;
}
  1. 重写- (CGPoint) targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity方法,保证每一次滑动后都有一个图片位于屏幕中心。
- (CGPoint) targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
    
    // 计算出最终显示的矩形框
    CGRect rect;
    rect.size = self.collectionView.frame.size;
    rect.origin.x = proposedContentOffset.x;
    rect.origin.y = 0;
    
    // 获取布局
    NSArray* array = [super layoutAttributesForElementsInRect:rect];
    
    // 获取collectionView最中心点的x值
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width / 2;
    
    CGFloat minDatle = MAXFLOAT;
    for (UICollectionViewLayoutAttributes* attributes in array) {
        if (ABS(minDatle) > ABS(attributes.center.x - centerX)) {
            minDatle = attributes.center.x - centerX;
        }
    }
    
    // 修正偏移量,保证有一个图片位于屏幕中心
    proposedContentOffset.x += minDatle;
    
    return proposedContentOffset;
}

结果展示:
在这里插入图片描述

三. 将两个合起来,将轮播图加入总的collectionView中。

  1. 为轮播图定义一个cell。

cell.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface BookShowCell : UICollectionViewCell
<
UICollectionViewDelegate,
UICollectionViewDataSource
>

@property (nonatomic, strong) UICollectionView* collectionView;

@end

NS_ASSUME_NONNULL_END

cell.h

#import "BookShowCell.h"
#import "MyLayout.h"
#import "BookcaseCell.h"

@implementation BookShowCell

- (instancetype) initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initCollectionView];
    }
    return self;
}

- (void) initCollectionView {
    MyLayout* layout = [[MyLayout alloc] init];
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    [self.collectionView registerClass:[BookcaseCell class] forCellWithReuseIdentifier:@"bookcase"];
    
    [self.contentView addSubview:self.collectionView];
}

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

- (__kindof UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BookcaseCell* cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"bookcase" forIndexPath:indexPath];
    
    if (indexPath.row % 2 == 0) {
        [cell.imageView setImage:[UIImage imageNamed:@"book.jpeg"]];
    } else {
        [cell.imageView setImage:[UIImage imageNamed:@"book2.jpeg"]];
    }
    
    return cell;
}

@end
  1. 为总的collectionView自定义一个layout,因为item的大小不一样了。需要把轮播图的item放大。
    layout.m
#import "FaceLayout.h"

@implementation FaceLayout

- (void) prepareLayout {
    [super prepareLayout];
}

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes*> *) layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray* arr = [[NSArray alloc] initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:YES];
    
    for (UICollectionViewLayoutAttributes* attributes in arr) {
        if (attributes.indexPath.row == 0) {
            attributes.transform = CGAffineTransformMakeScale(2.2, 2.2);
        }
    }
    
    return arr;
}

@end
  1. 将使用新定一的layout建立总的collectionView,并注册轮播图的cell。
UICollectionViewFlowLayout* layout = [[FaceLayout alloc] init];

self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];

[self.collectionView registerClass:[BookShowCell class] forCellWithReuseIdentifier:@"bookShow"];
  1. 加入轮播图的cell。
- (__kindof UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        BookShowCell* cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"bookShow" forIndexPath:indexPath];
        
        return cell;
    } else {
        BookcaseFaceCell* cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"bookcaseFace" forIndexPath:indexPath];
        return cell;
    }
}

效果图
在这里插入图片描述

图片根据距离中心点的距离不同调整大小

在这里插入图片描述

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

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

相关文章

[ 数据结构 -- 手撕排序算法第五篇 ] 堆排序

文章目录前言一、常见的排序算法二、堆的概念及结构三、堆的实现3.1 堆的插入3.2 堆的删除四、堆排序4.1 向上调整建堆4.2 向下调整建堆4.3 建堆的时间复杂度4.4 堆排序五、堆排序的特性前言 手撕排序算法第五篇&#xff1a;堆排序&#xff01; 从本篇文章开始&#xff0c;我会…

Java+JSP超市管理系统(含源码+论文+答辩PPT等)

项目功能简介: 该项目采用的技术后台框架&#xff1a;Servlet、JSP、JDBC、UI界面&#xff1a;BootStrap、jQuery、数据库&#xff1a;MySQL 系统功能 该系统共包含两种角色&#xff1a;员工和管理员。系统的主要功能模块如下&#xff1a; 1.系统管理 系统登陆、系统退出、修改…

《Mysql是怎样运行的》补充

19 第19章 从猫爷被杀说起-事务简介 19.1 事务的起源 19.1.1 原子性&#xff08;Atomicity&#xff09; 19.1.2 隔离性&#xff08;Isolation&#xff09; 其它的状态转换不会影响到本次状态转换&#xff0c;这个规则被称之为 隔离性 19.1.3 一致性&#xff08;Consisten…

[ISITDTU 2019]EasyPHP rce替换字母

<?php highlight_file(__FILE__);$_ $_GET[_]; if ( preg_match(/[\x00- 0-9\"$&.,|[{_defgops\x7F]/i, $_) )die(ros will not do it);if ( strlen(count_chars(strtolower($_), 0x3)) > 0xd )die(you are so close, omg);eval($_); ?> 打开界面有两个i…

Mysql分布式锁(四)乐观锁实现并发

文章目录CAS - Compare And Swap业务改造1. 表结构新增version列2. 修改代码3. 测试问题1. 高并发情况下&#xff0c;性能极低2. ABA问题3. 读写分离情况下导致乐观锁不可靠CAS - Compare And Swap 先比较再交换&#xff0c;一般通过时间戳或者version版本号。 举例&#xff1…

【审计思路】如何快速定位SQLMS注入漏洞?

0x00 前言 MCMS是政府、教育等其他行业常用的CMS&#xff0c;应用广泛&#xff0c;但是底层的代码中仍然遗留不少的问题。这篇文章主要针对SQL注入进行审计并探讨如何快速定位SQL注入漏洞&#xff0c;以及其他工具的应用。 MCMS&#xff0c;是完整开源的Java CMS&#xff01;基…

[ vulhub漏洞复现篇 ] Apache Airflow Celery 消息中间件命令执行漏洞复现 CVE-2020-11981

&#x1f36c; 博主介绍 &#x1f468;‍&#x1f393; 博主介绍&#xff1a;大家好&#xff0c;我是 _PowerShell &#xff0c;很高兴认识大家~ ✨主攻领域&#xff1a;【渗透领域】【数据通信】 【通讯安全】 【web安全】【面试分析】 &#x1f389;点赞➕评论➕收藏 养成习…

基于asp.net企业网上办公自动化系统-计算机毕业设计

企业网上办公自动化通过对各办公自动化要素的闭环整合&#xff0c;实现了工作流、信息流、知识流和办公自动化系统的整合管理&#xff0c;提供了一个科学、开放、先进的信息化办公平台&#xff0c;实现办公自动化&#xff0c;并进行远程办公或在家办公。企业网上办公自动化将人…

redis开启二级缓存

目录 1. redis集成 2. pom.xml加入redis缓存支持 3. 在项目配置文件中加入cache配置 4. 在启动类开发缓存功能 5. 需要缓存的实体对象实现序列化接口 6. 缓存的使用 7. 测试 今天与大家分享&#xff0c;redis二级缓存实现案例。如有问题&#xff0c;望指教。 1. redis集…

计算机毕业设计springboot+vue基本微信小程序的校园二手物品交易平台系统

项目介绍 目的:设计一个同学们能自由发布和浏览求购或卖出商品信息的校园二手交易小程序,解决信息的不流通以及传统二手商品信息交流方式的笨拙等问题。 意义:在大学校园里,存在着很多的二手商品,但是由于信息资源的不流通以及传统二手商品信息交流方式的笨拙,导致了很多仍然具…

十年阿里测试工程师浅谈UnitTest单元测试框架

一、UnitTest单元测试框架提供了那些功能 1.提供用例组织和执行 如何定义一条“测试用例”? 如何灵活地控制这些“测试用例”的执行? 2.提供丰定的断言方法 当测试用例的执行结果与预期结果不一致时&#xff0c;判定测试用例失败。在自动化测试中&#xff0c;通过“断言”…

2022 软件测试简答题【太原理工大学】

四、简答题 1. 比较自顶向下集成测试方法和自底向上集成测试方法各自的优缺点。 ① 自顶向下集成 优点&#xff1a;较早地验证了主要控制和判断点:按深度优先可以首先实现和验证一个完整的软件功能;功能较早证实&#xff0c;带来信心;只需一个驱动&#xff0c;减少驱动器开发…

python+pyqt5设置窗体图标和任务栏图标及窗体标题的方法

本次设置窗体标题只用了一种方法&#xff0c;在进行窗体实例化后window Window()&#xff0c;使用setWindowTitle(str)命令&#xff0c;在主程序中的设置命令如下所示&#xff1a; if __name__ __main__:QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) #Qt从5.6.0开…

机器学习——05线性回归

机器学习——05线性回归 参考资料 AIlearningMachine-Learning-in-Action庞善民.西安交通大学机器学习导论2022春PPT 使用Jupyter进行练习&#xff0c;python3 具体项目地址&#xff1a;https://github.com/yijunquan-afk/machine-learning/tree/master/basic-learn/05-reg…

ARM S5PV210 X210 刷机教程总结

前言 S5PV210 X210 开发板外观介绍 一、开发板刷系统1 1. 什么是刷系统 刷系统就是利用刷机工具&#xff0c;向开发板中烧录预先编译好的系统镜像&#xff0c;使之在开发板上运行起来。 2. 串口输出的意义&#xff08;做系统控制台&#xff09; 串口是一种硬件通信口&…

【将高光谱、多光谱和全色图像进行融合】

HyperNet: A deep network for hyperspectral, multispectral, and panchromatic image fusion &#xff08;HyperNet&#xff1a;一种用于高光谱、多光谱和全色图像融合的深度网络&#xff09; 传统的方法主要是将高光谱图像&#xff08;hyperspectral image (HSI)&#xff0…

定时红绿灯(C51单片机)

一&#xff0e;项目题目&#xff1a;利用中断处理制作的定时LED红绿灯系统 二&#xff0e;项目器件&#xff1a; 红色LED灯 绿色LED灯 黄色LED灯 100R电阻 电源 电容器 C51单片机 接地线 三&#xff0e;项目原理图 四&#xff0e;项目实现功能&#xff1a; 使用定时器/计数…

【云原生 | Kubernetes 实战】14、K8s 控制器 Statefulset 入门到企业实战应用

目录 一、Statefulset 控制器&#xff1a;概念、原理解读 1.1 什么是有状态服务&#xff1f; 1.2 什么是无状态服务&#xff1f; 二、 Statefulset 资源清单文件编写技巧 三、Statefulset 使用案例&#xff1a;部署 web 站点 3.1 StatefulSet 由以下几个部分组成&#xf…

VMware克隆虚拟机

一、克隆虚拟机 1. 在WMware中&#xff0c;右键虚拟机模板&#xff08;需要克隆的虚拟机原型&#xff09;&#xff0c;选择&#xff1a;管理 ----> 克隆&#xff0c;如下图所示&#xff1a; 2. 然后&#xff0c;如下图进行操作&#xff1a; 二、扩展&#xff1a;移除、删除…

【Python】 14-CVS文件操作

1.CVS文件 值没有类型&#xff0c;所有东西都是字符串&#xff1b; • 没有字体大小或颜色的设置&#xff1b; • 没有多个工作表&#xff1b; • 不能指定单元格的宽度和高度&#xff1b; • 不能合并单元格&#xff1b; • 不能嵌入图像或图表。 CSV 文件中的每个单元格 有逗…