本篇博客应该算的上CollectionView的高级应用了,从iOS开发之窥探UICollectionViewController(一)到今天的(五),可谓是由浅入深的窥探了一下UICollectionView的用法,这些用法不仅包括SDK中自带的流式布局(UICollectionViewDelegateFlowLayout)而且介绍了如何根据你的需求去自定义属于你自己的CollectionView。自定义的CollectionView可谓是非常灵活,其灵活性也决定了其功能的强大。CollectionView的自定义就是其Cell高度可定制的属性,通过对Cell赋值不同的属性来达到自定义的目的。
在上篇博客《iOS开发之窥探UICollectionViewController(四) --一款功能强大的自定义瀑布流》中,通过自定义的CollectionView创建了一个可定制的自定义瀑布流,效果还是蛮ok的。本篇博客是使用自定义CollectionView的另一个实例,自定义CollectionView的方式和上一篇是一致的,都是重写UICollectionViewLayout相应的方法,然后再通过委托回调来设置布局的参数。自定义CollectionView的思路是一样的,只是具体的实现方式不同。学习么,要学会举一反三,希望大家能通过这两篇自定义CollectionView的博客来写出属于你自己的自定义效果。
一.效果展示
废话少说,进入今天博客的主题,下方就是今天博客中Demo的运行效果。虽然运行效果做成gif丢帧了,看起来有些卡,不过跑起来还是比较流畅的。切换图片时进行一个360度的旋转,并且修改Cell的层级,当前显示的图片层级最高。并且移动时,如果要显示的图片不在屏幕中央就做一个位置矫正。点击图片时,使用仿射变换使其放大,再点击使其缩小。接下来将会详细的介绍其实现方案。
二.该自定义布局的使用方式
我们先看一下该自定义布局是如何使用的,然后再通过使用方式来逐步介绍它是如何实现的。这也是一个由浅入深的过程,因为用起来要比做起了更容易。比如开汽车容易,造汽车可就麻烦多了。所以在本篇博客的第二部分,将要介绍如何去使用该自定义组件。
其实所有CollectionView的自定义布局的使用方式都是一样的,分为以下几步:
1.为我们的CollectionView指定该布局,本篇博客的CollectionView是通过Storyboard来实现的,所以我们可以通过Storyboard来指定自定义的布局文件,如果你是使用纯代码方式,可以在CollectionView实例化时来指定所需的布局。下方是使用Storyboard来指定的布局文件,需要把Layout选项调到Custom下,然后下方的Class选项就是你要关联的自定义布局文件,具体如下所示。代码的就在此不做赘述了,网上一抓一大把。
2.给Storyboard上的CollectionViewController关联一个类,然后我们就可以使用自定义的布局了。获取指定的自定义布局对象,然后指定委托代理对象,如下所示:
1- (void)viewDidLoad {2[super viewDidLoad];34_customeLayout = (CustomTransformCollecionLayout *) self.collectionViewLayout;5_customeLayout.layoutDelegate =self;6}
3.除了实现CollectionView的DataSource和Delegate, 我们还需实现布局的代理方法,该自定义布局要实现的代理方法如下。第一个是设置Cell的大小,也就是宽高。第二个是设置Cell间的边距。
1#PRagmamark <CustomTransformCollecionLayoutDelegate>23- (CGSize)itemSizeWithCollectionView:(UICollectionView *)collectionView4collectionViewLayout:(CustomTransformCollecionLayout *)collectionViewLayout {5returnCGSizeMake(200,200);6}78- (CGFloat)marginSizeWithCollectionView:(UICollectionView *)collectionView9collectionViewLayout:(CustomTransformCollecionLayout *)collectionViewLayout {10return10.0f;11}
4.点击Cell放大和缩小是在UICollectionViewDataSource中点击Cell的代理方法中做的,在此就不做赘述了,详见GitHub上分享的链接。
三. 如何实现
上面介绍了如何去使用该自定义组件,接下来就是“造车”的过程了。本篇博客的第三部分介绍如何去实现这个自定义布局。
1. CustomTransformCollecionLayout头文件中的代码如下所示,该文件中定义了一个协议,协议中的方法就是在CollectionView中要实现的那两个代理方法。这些代理方法提供了Cell的大小和边距。该文件的接口中定义了一个代理对象,当然为了强引用循环,该代理对象是weak类型的。
1//2//CustomTransformCollecionLayout.h3//CustomTransformCollecionLayout4//5//Created by Mr.LuDashi on 15/9/24.6//Copyright (c) 2015年 ZeluLi. All rights reserved.7//89#import<UIKit/UIKit.h>1011#defineSCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width12#defineSCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height1314@classCustomTransformCollecionLayout;1516@protocolCustomTransformCollecionLayoutDelegate <NSObject>17/**18* 确定cell的大小19*/20- (CGSize) itemSizeWithCollectionView:(UICollectionView *)collectionView21collectionViewLayout:(CustomTransformCollecionLayout *)collectionViewLayout;2223/**24* 确定cell的大小25*/26- (CGFloat) marginSizeWithCollectionView:(UICollectionView *)collectionView27collectionViewLayout:(CustomTransformCollecionLayout *)collectionViewLayout;2829@end3031@interfaceCustomTransformCollecionLayout : UICollectionViewLayout3233@property (nonatomic, weak)id<CustomTransformCollecionLayoutDelegate>layoutDelegate;3435@end
2.接下来介绍一下CustomTransformCollecionLayout实现文件也就是.m中的代码,其中的延展中的属性如下所示。numberOfSections:该参数代表着CollectionView的Section的个数。numberOfCellsInSection:代表着每个Section中Cell的个数。itemSize则是Cell的尺寸(宽高),该属性的值是由布局代理方法提供。itemMargin: 该属性是Cell的边距,它也是通过布局的代理方法提供。itemsX: 用来存储计算的每个Cell的X坐标。
1//2//CustomTransformCollecionLayout.m3//CustomTransformCollecionLayout4//5//Created by Mr.LuDashi on 15/9/24.6//Copyright (c) 2015年 ZeluLi. All rights reserved.7//89#import"CustomTransformCollecionLayout.h"1011@interfaceCustomTransformCollecionLayout()1213@property (nonatomic) NSInteger numberOfSections;14@property (nonatomic) NSInteger numberOfCellsInSection;15@property (nonatomic) CGSize itemSize;16@property (nonatomic) CGFloat itemMargin;18@property (nonatomic, strong) NSMutableArray *itemsX;1920@end
3. 在实现中我们需要重写UICollectionViewLayout中相关的方法,需要重写的方法如下:
(1). 预加载布局方法, 该方法会在UICollectionView加载数据时执行一次,在该方法中负责调用一些初始化函数。具体如下所示。
1#pragmamark -- UICollectionViewLayout 重写的方法2- (void)prepareLayout {3[super prepareLayout];45[self initData];67[self initItemsX];8}
(2).下面的方法会返回ContentSize, 说白一些,就是CollectionView滚动区域的大小。
1/**2* 该方法返回CollectionView的ContentSize的大小3*/4-(CGSize)collectionViewContentSize {5CGFloat width = _numberOfCellsInSection * (_itemSize.width +_itemMargin);6returnCGSizeMake(width, SCREEN_HEIGHT);7}
(3).下方的方法是为每个Cell绑定一个UICollectionViewLayoutAttributes对象,用来设置每个Cell的属性。
1/**2* 该方法为每个Cell绑定一个Layout属性~3*/4- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {56NSMutableArray *array =[NSMutableArray array];78//add cells9for(inti =0; i < _numberOfCellsInSection; i++) {10NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];1112UICollectionViewLayoutAttributes *attributes =[self layoutAttributesForItemAtIndexPath:indexPath];1314[array addObject:attributes];15}16returnarray;17}
(4).下方这个方法是比较重要的,重写这个方法是为了为每个Cell设定不同的属性值。其中transform的值是根据CollectionView的滚动偏移量来计算的,所以在滚动CollectionView时,Cell也会跟着旋转。具体的实现方案在代码中添加了注释,如下所示:
1/**2* 为每个Cell设置attribute3*/4- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{56//获取当前Cell的attributes7UICollectionViewLayoutAttributes *attributes =[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];89//获取滑动的位移10CGFloat contentOffsetX =self.collectionView.contentOffset.x;11//根据滑动的位移计算当前显示的时第几个Cell12NSInteger currentIndex =[self countIndexWithOffsetX: contentOffsetX];13//获取Cell的X坐标14CGFloat centerX =[_itemsX[indexPath.row] floatValue];15//计算Cell的Y坐标16CGFloat centerY = SCREEN_HEIGHT/2;1718//设置Cell的center和size属性19attributes.center =CGPointMake(centerX, centerY);20attributes.size =CGSizeMake(_itemSize.width, _itemSize.height);2122//计算当前偏移量(滑动后的位置 - 滑动前的位置)23CGFloat animationDistance = _itemSize.width +_itemMargin;24CGFloat change = contentOffsetX - currentIndex * animationDistance + SCREEN_WIDTH /2- _itemSize.width /2;2526//做一个位置修正,因为当滑动过半时,currentIndex就会加一,就不是上次显示的Cell的索引,所以要减去一做个修正27if(change <0) {28change = contentOffsetX - (currentIndex -1) * animationDistance + SCREEN_WIDTH/2- _itemSize.width/2;29}3031if(currentIndex ==0&& contentOffsetX <=0) {32change =0;33}3435//旋转量36CGFloat temp = M_PI *2* (change / (_itemSize.width +_itemMargin));3738//仿射变换 赋值39attributes.transform =CGAffineTransformMakeRotation(temp);4041//把当前显示的Cell的zIndex设置成较大的值42if(currentIndex ==indexPath.row) {43attributes.zIndex =1000;44}else{45attributes.zIndex =currentIndex;46}4748returnattributes;49}
View Code
(5).要让Cell随着滚动旋转起来,你需要重写下面这个方法,并且返回YES。该方法返回YES意味着当滚动时,会再次执行上面(4)的方法,重新为每个Cell的属性赋值。所以重写下面的方法,并返回YES(下面的表达式也是一样的)才可以运动起来呢。
1//当边界发生改变时,是否应该刷新布局。如果YES则在边界变化(一般是scroll到其他地方)时,将重新计算需要的布局信息。2-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {3return!CGRectEqualToRect(newBounds, self.collectionView.bounds);4}
(6).重写下面的方法是为了修正CollectionView滚动的偏移量,使当前显示的Cell出现在屏幕的中心的位置,方法如下:
1//修正Cell的位置,使当前Cell显示在屏幕的中心2-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{345//计算显示的是第几个Cell6NSInteger index =[self countIndexWithOffsetX:proposedContentOffset.x];78CGFloat centerX = index * (_itemSize.width + _itemMargin) + (_itemSize.width/2);910proposedContentOffset.x = centerX - SCREEN_WIDTH/2;1112returnproposedContentOffset;13}
View Code
4.下方就是我自己实现的方法了,也就在重写的方法中调用的函数,具体如下。
1#pragmamark -- 自定义的方法2/**3* 根据滚动便宜量来计算当前显示的时第几个Cell4*/5-(NSInteger) countIndexWithOffsetX: (CGFloat) offsetX{6return(offsetX + (SCREEN_WIDTH /2)) / (_itemSize.width +_itemMargin);7}89/**10* 初始化私有属性,通过代理获取配置参数11*/12- (void) initData{13_numberOfSections =self.collectionView.numberOfSections;1415_numberOfCellsInSection = [self.collectionView numberOfItemsInSection:0];1617_itemSize =[_layoutDelegate itemSizeWithCollectionView:self.collectionView collectionViewLayout:self];1819_itemMargin =[_layoutDelegate marginSizeWithCollectionView:self.collectionView collectionViewLayout:self];2021}2223/**24* 计算每个Cell的X坐标25*/26- (void) initItemsX{27_itemsX =[[NSMutableArray alloc] initWithCapacity:_numberOfCellsInSection];2829for(inti =0; i < _numberOfCellsInSection; i ++) {30CGFloat tempX = i * (_itemSize.width + _itemMargin) + _itemSize.width/2;31[_itemsX addObject:@(tempX)];32}333435}
至此,Demo的代码讲解完毕,经过上述步骤,你就可以写出上面动画中的自定义效果了,具体代码会在github中进行分享。分享链接如下:
github上Demo的链接地址:https://github.com/lizelu/CustomTransformCollecionLayout