针对IOS6提出的全新特性UICollectionView做了一个实际的使用,有很多地方还是很有意义的,定制化貌似更加的灵活了,这样对于大量的自定义来说更是“万事俱备,东风已来”矣。在Apple Developer 中心也有Demo,那个Demo也是很有意思的,文章最后会给出下载地址。
一、战果展示,呵呵~~
实现了一个圆形的UICollectionView的使用,当触摸非圆周的部分时,Cell会增加,这里注意每个小图片就是一个cell;当触摸圆周上的cell,也就是小图片的时候,对应的cell就会消除。至于中间那个,嘿嘿~~是实现的一个gif效果显示。这里分享一个IOS设备上实现gif效果图的图片获取方法。将一张gif图片在MAC机上使用系统自带的“预览”打开,就可以看到一张一张的图片了。然后按照顺序“另存为”即可拿到顺序的图片了。接下来就可以参照 ios上实现gif显示效果 这里进行设置了。祝愉快~~~
二、代码分析
1.1 代理方法介绍(AppDelegate)
在AppDelegate里面,方法didFinishLaunchingWithOption中,创建ViewController,这个Controller是继承自UICollectionViewController的,并且初始化controller的使用需要制定Controller的Layout,这个Layout就是制定CollectionView里面的cells和supplementary views的。
样例代码:
[cpp]
#import "AppDelegate.h"
#import "ViewController.h"
#import "CircleLayout.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithCollectionViewLayout:[[CircleLayout alloc] init]];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
1.2 自定义Layout类介绍(CircleLayout)
在上面代码中,可以看到引入了一个类CircleLayout.h ,这个类的作用就是指定页面的Layout样式的。从结果图上可以看到,这个类里面至少要实现cell的样式、collectionView的样式。要实现的东西不少~~~
CircleLayout类是继承自UICollectionViewLayout的,而UICollectionViewLayout类是一个抽象基类,通过继承它可以生成collectionView的Layout信息。而Layout的作用就是决定CollectionView中的Cell、supplementary view、decoration view的位置的。在使用UICollectionViewLayout的时候,必须谨记“先子类化,后使用” !
1.2.1 子类化
在子类化UICollectionViewLayout的时候,需要注意:
aa Layout只负责布局样式,而不负责创建view。(view的创建是通过代理方法 datasource来实现的)
bb Layout对象中定义了view的位置以及view大小size的信息
1.2.2 UICollectionView 的三要素介绍
Cells:Layout就像一个管理者,而cell就是被管理者,每一个cell代表了collectionview中的一个item,一个collectionview可以放在一个section中,也可以放在整个UICollectionview中。使用和位置都是由Layout对象定义的。
Supplementary Views:纯属显示的一个要素,不能被用户选择,而且还是可有可无的。只要你想为Section或者整个collection view 添加页眉和页脚,它就是了。
Decoration Views:一个装饰品,不可被用户选择,类似于Supplementary View,使用和位置都是由Layout定义的。可有可无。
1.2.3 需要重载的方法介绍
每一个管理者(Layout对象)都有自己的一套方法,来管理手下的虾兵小将:
1. collectionViewContentSize
2. shouldInvalidateLayoutForBoundsChange:
3. layoutAttributesForElementsInRect:
4. layoutAttributesForItemAtIndexPath:
5. layoutAttributesForSupplementaryViewOfKind:atIndexPath: (如果layout 支持 supplementary views)
6.layoutAttributesForDecorationViewWithReuseIdentifier:atIndexPath: (如果layout 支持 decoration views)
上述方法的具体含义和作用,可参考 SDK
1.2.4 折腾“插入”和"删除 "
当collection view 中的数据发生了变化,例如其中的item有了变化,collection view 都需要重新检索相应的Layout信息,来得到新的显示。这样collection view 就有了自己的一套检索的方法,你只需要进行重载就可以了。
initialLayoutAttributesForInsertedItemAtIndexPath:
initialLayoutAttributesForInsertedSupplementaryElementOfKind:atIndexPath:
finalLayoutAttributesForDeletedItemAtIndexPath:
finalLayoutAttributesForDeletedSupplementaryElementOfKind:atIndexPath:
但是这里只需要进行简单的实现,所以只需要重载一下两个方法:
initialLayoutAttributesForInsertedItemAtIndexPath:
finalLayoutAttributesForDeletedItemAtIndexPath:
OK,这就是自定义的CircleLayout类中需要注意的。下来上code:
CircleLayout.h 文件:
[cpp]
#import <UIKit/UIKit.h>
@interface CircleLayout : UICollectionViewLayout
//定义圆的圆心、半径,以及cell的个数
@property (nonatomic,assign) CGPoint center;
@property (nonatomic,assign) CGFloat radius;
@property (nonatomic,assign) NSInteger cellCount;
@end
CircleLayout.m文件:
[cpp]
#import "CircleLayout.h"
//定义item的大小
#define ITEM_SIZE 70
@implementation CircleLayout
//为创建Circle做准备
- (void)prepareLayout{
[super prepareLayout];
CGSize size = self.collectionView.frame.size;
_cellCount = [[self collectionView] numberOfItemsInSection:0];
_center = CGPointMake(size.width / 2.0, size.height / 2.0);
_radius = MIN(size.width, size.height) / 2.5;
}
//设置collectionViewContentsize
- (CGSize) collectionViewContentSize{
return self.collectionView.frame.size;
}
//设置UICollectionViewLayoutAttributes
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attributes.size = CGSizeMake(ITEM_SIZE, ITEM_SIZE);
attributes.center = CGPointMake(_center.x + _radius * cosf(2 * indexPath.item * M_PI / _cellCount),
_center.y + _radius * sinf(2 * indexPath.item * M_PI / _cellCount));
return attributes;
}
//设置layoutAttributesForElementsInRect
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
NSMutableArray *attributes = [NSMutableArray array];
for(NSInteger i = 0; i < self.cellCount; i++){
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
[attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
}
return attributes;
}
#pragma mark --
#pragma mark Layout init & final
//复写initialLayoutAttributesForInsertedItemAtIndexPath
- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForInsertedItemAtIndexPath:(NSIndexPath *)itemIndexPath
{
UICollectionViewLayoutAttributes* attributes = [self layoutAttributesForItemAtIndexPath:itemIndexPath];
attributes.alpha = 0.0;
attributes.center = CGPointMake(_center.x, _center.y);
return attributes;
}
//复写finalLayoutAttributesForDeletedItemAtIndexPath
- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDeletedItemAtIndexPath:(NSIndexPath *)itemIndexPath
{
UICollectionViewLayoutAttributes* attributes = [self layoutAttributesForItemAtIndexPath:itemIndexPath];
attributes.alpha = 0.0;
attributes.center = CGPointMake(_center.x, _center.y);
attributes.transform3D = CATransform3DMakeScale(0.1, 0.1, 1.0);
return attributes;
}
@end
1.3 自定义Cell
关于UITableViewCell的自定义,估计大多数人都会不止一种的自定义方法吧,UICollectionViewCell也可以定制,这样就极大的方便了那些需要震撼性UI的App开发者的使用了。UICollectionViewCell的主要功能就是管理collectionview中的每一个item了,注意只是当item在屏幕的可视范围的时候,OK,那么自定义的这个Cell就直接继承自UICollectionViewCell类,在这个自定义的Cell中需要一个图像容器UIImageView来存放每一个item上的图片。
[cpp]
#import <UIKit/UIKit.h>
@interface CircleCell : UICollectionViewCell
@property (nonatomic,strong) UIImageView *imageView;
@end
[cpp]
#import "CircleCell.h"
#import <QuartzCore/QuartzCore.h>
@implementation CircleCell
@synthesize imageView;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.contentView.layer.cornerRadius = 10.0f;
self.contentView.frame = CGRectMake(0, 0, 75, 75);
self.contentView.layer.borderWidth = 1.0f;
self.contentView.layer.borderColor = [UIColor whiteColor].CGColor;
self.contentView.backgroundColor = [UIColor underPageBackgroundColor];
self.imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1_120103225810_1.jpeg"]];
self.imageView.layer.masksToBounds = YES;
self.imageView.layer.cornerRadius = 10.0f;
self.imageView.frame = self.contentView.frame;
[self.contentView addSubview:self.imageView];
}
return self;
}
@end
完成之后,就完成了大部分的code准备工作了。接下来就是要在开始那个ViewController类中进行调用使用了。
三、最终的code
首先要实现UICollectionView的两个代理方法:delegate & dataSource。并且要给collectionView 添加Tap 手势哦,这样才能让用户在触摸的时候有所交互。
直接上code吧。HOHO~~
ViewController.h 文件:
[cpp]
#import <UIKit/UIKit.h>
@interface ViewController : UICollectionViewController
@property (nonatomic,assign)NSInteger cellCount;
@end
ViewController.m 文件:
[cpp] view plaincopy
#import "ViewController.h"
#import "GifLayoutView.h"
#import "CircleCell.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//添加背景gif显示图View
GifLayoutView *gifView = [[GifLayoutView alloc]initWithFrame:CGRectMake(0, 0, 350, 350)];
gifView.center = self.collectionView.center;
[self.collectionView addSubview:gifView];
//为collectionView添加tapGesture,并注册。
self.cellCount = 20;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
[self.collectionView addGestureRecognizer:tapGesture];
[self.collectionView registerClass:[CircleCell class] forCellWithReuseIdentifier:@"Circle_Cell"];
[self.collectionView reloadData];
self.collectionView.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
}
//设置numberOfItemsInSection
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
return self.cellCount;
}
//复用Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CircleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Circle_Cell" forIndexPath:indexPath];
return cell;
}
//手势的相应事件
- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded)
{
CGPoint initialPinchPoint = [sender locationInView:self.collectionView];
NSIndexPath* tappedCellPath = [self.collectionView indexPathForItemAtPoint:initialPinchPoint];
if (tappedCellPath!=nil)
{
self.cellCount = self.cellCount - 1;
[self.collectionView performBatchUpdates:^{
[self.collectionView deleteItemsAtIndexPaths:[NSArray arrayWithObject:tappedCellPath]];
} completion:nil];
}
else
{
self.cellCount = self.cellCount + 1;
[self.collectionView performBatchUpdates:^{
[self.collectionView insertItemsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForItem:0 inSection:0]]];
} completion:nil];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end