一個App受歡迎的程度,一方面來源于它本身為使用者提供便捷的功能,另一方面則來源于它的UI。UI是使用者體驗重要的組成部分,構成UI的的元素恰恰離不開那些看似獨立的控件。在開發的過程中,大家對UITableView應該很熟悉吧!确實UITableView在處理資料顯示方面有着很強大的功能,例如網紅們使用的微網誌,微信社交軟體的聊天界面等等,這種流式布局使用UITableView簡直最合适不過了;但畢竟UITableView不是萬能的,當需要顯示橫縱向的資料時它就顯得捉襟見肘了,雖然這也難不倒我們程式猿但是何必要大費周章的去定義複雜的cell呢!UICollectionView就是專門用來應付這種布局的,使用UICollectionView可以給我們帶來以下幾點優勢:1.可以高度的定制内容展示的樣式 2.高效的管理大量的資料。如果大家想加深層次去了解UICollectionView,可以看下這篇文章。
首先給大家看一下這個Demo的效果圖:
iOS裝置不知道現在有沒有可以螢幕錄制的app,這樣我就可以把操作的動作用gif圖檔po上來了,大家如果有推薦可以告訴我哈!關于拖動,長按圖檔後就可以将圖檔拖到你想要的位置上,另外的圖檔則會依次排序,很順暢的體驗。
在使用UICollectionView的時後,我們的類需要實作這些協定:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,
UICollectionViewDelegate,UIGestureRecognizerDelegate。
UICollectionViewDataSource:和我們在UITableView中所需要實作的UITableViewDataSource是一個道理,它裡面包括以下這些API:
@protocol UICollectionViewDataSource <NSObject>
@required
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
@optional
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;
// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0);
@end
UICollectionViewDelegateFlowLayout:UICollectionViewFlowLayout是一個專門用來管理collectionView布局的類,可以通過實作以下函數來調
整我們界面的樣式:
@protocol UICollectionViewDelegateFlowLayout <UICollectionViewDelegate>
@optional
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;
@end
UICollectionViewDelegate:和UITableViewDelegate一樣,這裡就把它協定裡面的的函數po出來了,通過重寫裡面的函數,我們可以實作cell的點
擊與拖動。
UIGestureRecognizerDelegate:由于我們還有一個拖動的功能,是以需要實作使用者手勢的協定。
好了,基礎的概念講了,現在我們就開始動手實作他吧!老樣子直接看源碼:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//設定背景色
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"back.jpg"]]];
//設定資料源
self.dataSource = [[NSMutableArray alloc] initWithObjects:
@"1.png",@"2.png",@"3.png", @"4.png", @"5.png", @"6.png", @"7.png", @"8.png", @"9.png", @"10.png", @"11.jpg", @"12.JPG",
@"13.JPG", @"14.jpg", @"15.JPG", @"16.png", @"17.png", @"18.png", @"19.png", @"20.png", nil];
//初始化布局
self.flow = [[UICollectionViewFlowLayout alloc] init];
self.collect = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flow];
[self.collect setBackgroundColor:[UIColor clearColor]];
//注冊cell 這一步必須要實作
[self.collect registerClass:[CustomCollectionCell class] forCellWithReuseIdentifier:@"CustomCell"];
self.collect.delegate = self;
self.collect.dataSource = self;
[self.collect setFrame:self.view.bounds];
//添加長按手勢
self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] init];
[self.longPressGestureRecognizer addTarget:self action:@selector(handleLongPressRecognizer:)];
[self.collect addGestureRecognizer:self.longPressGestureRecognizer];
[self.view addSubview:self.collect];
}
在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
以上這些就是構成該Demo的重要組成部分了,UICollectionView還有很多的要素在這裡面沒有講到,往後我還會再研究這個控件更加進階的
的使用,本篇就好比是餐前的開胃小菜吧,希望大家喜歡。附上這個例子的源碼:
@implementation ViewController
@synthesize dataSource = _dataSource;
@synthesize longPressGestureRecognizer = _longPressGestureRecognizer;
@synthesize flow = _flow;
@synthesize collect = _collect;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//設定背景色
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"back.jpg"]]];
//設定資料源
self.dataSource = [[NSMutableArray alloc] initWithObjects:
@"1.png",@"2.png",@"3.png", @"4.png", @"5.png", @"6.png", @"7.png", @"8.png", @"9.png", @"10.png", @"11.jpg", @"12.JPG",
@"13.JPG", @"14.jpg", @"15.JPG", @"16.png", @"17.png", @"18.png", @"19.png", @"20.png", nil];
//初始化布局
self.flow = [[UICollectionViewFlowLayout alloc] init];
self.collect = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flow];
[self.collect setBackgroundColor:[UIColor clearColor]];
//注冊cell 這一步必須要實作
[self.collect registerClass:[CustomCollectionCell class] forCellWithReuseIdentifier:@"CustomCell"];
self.collect.delegate = self;
self.collect.dataSource = self;
[self.collect setFrame:self.view.bounds];
//添加長按手勢
self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] init];
[self.longPressGestureRecognizer addTarget:self action:@selector(handleLongPressRecognizer:)];
[self.collect addGestureRecognizer:self.longPressGestureRecognizer];
[self.view addSubview:self.collect];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (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;
}
}
#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.dataSource.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CustomCollectionCell * cell = (CustomCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];
UIImage *image = [UIImage imageNamed:[self.dataSource objectAtIndex:indexPath.row]];
[cell setImageWithText:image text:@""];
return cell;
}
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath{
id item = [self.dataSource objectAtIndex:sourceIndexPath.item];
[self.dataSource removeObject:item];
[self.dataSource insertObject:item atIndex:destinationIndexPath.item];
}
#pragma mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
TestViewController *test = [[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];
NSString *imageName = [self.dataSource objectAtIndex:indexPath.row];
test.imageName = imageName;
[self.navigationController pushViewController:test animated:YES];
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
//選中放大效果
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
// CustomCollectionCell * cell = (CustomCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
//
// [UIView animateWithDuration:1 animations:^{
// cell.transform = CGAffineTransformMakeScale(2.0f, 2.0f);
// }];
}
//縮小效果
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
// CustomCollectionCell * cell = (CustomCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
//
// [UIView animateWithDuration:1 animations:^{
// cell.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
// }];
}
#pragma mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100, 100);
}
/*
* 上左下右間距
*/
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(15, 15, 15, 15);
}
/*
* item space
*/
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
return 8;
}
/*
* 行距 20
*/
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
return 10;
}
大家可以關注我的微信公衆号與我互動,相關問題也可以直接用公衆号聯系我: