在viewDidLoad函数中,初始化了一个UICollectionViewFlowLayout布局,并且需要配合UICollectionView来使用,两者加一起来使用才能“完美”,想比UITableView 中Cell使用的不同,在UICollectionView中必须先对Cell进行注册(RegisterClass),不然会在运行过程中报错。如何使排列的图片可以拖动呢,在这里我为UICollectionView添加了一个长按手势UILongPressGestureRecognizer。当我们长按时会触发handleLongPressRecognizer,代码如下:
- (void)handleLongPressRecognizer:(UILongPressGestureRecognizer *)gesture{
switch (gesture.state) {
case UIGestureRecognizerStateBegan:{
NSIndexPath *path = [self.collect indexPathForItemAtPoint:[gesture locationInView:gesture.view]];
if(path == nil){
break;
}
[self.collect beginInteractiveMovementForItemAtIndexPath:path];
}
break;
case UIGestureRecognizerStateChanged:
[self.collect updateInteractiveMovementTargetPosition:[gesture locationInView:gesture.view]];
break;
case UIGestureRecognizerStateEnded:
[self.collect endInteractiveMovement];
break;
default:
[self.collect cancelInteractiveMovement];
break;
}
}
好看的界面才能抓住用户的心,这里我自定义了Cell继承自UICollectionViewCell,cell中展示的图片会根据自身图片的大小进行按比例缩放,这样我们的桌面看上去就会有横版图片与竖版图片,如果不自定义的话就都是方方正正的九宫格,还是花点心思自定义一下显示效果吧!CustomCollectionCell的的代码如下:
#import "CustomCollectionCell.h"
@implementation CustomCollectionCell
@synthesize imageV = _imageV;
@synthesize labelV = _labelV;
@synthesize boundView = _boundView;
- (id)initWithFrame:(CGRect) frame{
self = [super initWithFrame:frame];
//init attributes
if(self){
[self setBackgroundColor:[UIColor clearColor]];
self.imageV = [[UIImageView alloc] initWithFrame:CGRectZero];
self.labelV = [[UILabel alloc] initWithFrame:CGRectZero];
self.boundView = [[UIView alloc] initWithFrame:CGRectZero];
[self.boundView setBackgroundColor:[UIColor whiteColor]];
[self.boundView addSubview:self.imageV];
[self addSubview:self.boundView];
[self addSubview:self.labelV];
}
return self;
}
- (void)setImageWithText:(UIImage *)image text:(NSString *)text{
if(!image){
return;
}
CGFloat imgWidth = image.size.width;
CGFloat imgHeight = image.size.height;
CGFloat iconWidth = 0.0;
CGFloat iconHeight = 0.0;
if(imgWidth > imgHeight){
iconHeight = roundf(((self.frame.size.width - 16)*imgHeight)/imgWidth);
iconWidth = self.frame.size.width - 16;
[self.boundView setFrame:CGRectMake(0, self.frame.size.height - iconHeight - 16, iconWidth + 16, iconHeight + 16)];
[self.imageV setFrame:CGRectMake(8, 8, iconWidth, iconHeight)];
}else{
iconWidth = roundf(((self.frame.size.width - 16) *imgWidth)/imgHeight);
iconHeight = self.frame.size.height - 16;
[self.boundView setFrame:CGRectMake(roundf((self.frame.size.width - iconWidth)/2), 0, iconWidth + 16, iconHeight + 16)];
[self.imageV setFrame:CGRectMake(8, 8, iconWidth, iconHeight)];
}
[self.imageV setImage:image];
}
@end










