使用iOS控件UICollectionView生成可拖動(dòng)的桌面的實(shí)例
一個(gè)App受歡迎的程度,一方面來源于它本身為用戶提供便捷的功能,另一方面則來源于它的UI。UI是用戶體驗(yàn)重要的組成部分,構(gòu)成UI的的元素恰恰離不開那些看似獨(dú)立的控件。在開發(fā)的過程中,大家對(duì)UITableView應(yīng)該很熟悉吧!確實(shí)UITableView在處理數(shù)據(jù)顯示方面有著很強(qiáng)大的功能,例如網(wǎng)紅們使用的微博,微信社交軟件的聊天界面等等,這種流式布局使用UITableView簡(jiǎn)直最合適不過了;但畢竟UITableView不是萬能的,當(dāng)需要顯示橫縱向的數(shù)據(jù)時(shí)它就顯得捉襟見肘了,雖然這也難不倒我們程序猿但是何必要大費(fèi)周章的去定義復(fù)雜的cell呢!UICollectionView就是專門用來應(yīng)付這種布局的,使用UICollectionView可以給我們帶來以下幾點(diǎn)優(yōu)勢(shì):1.可以高度的定制內(nèi)容展示的樣式 2.高效的管理大量的數(shù)據(jù)。
首先給大家看一下這個(gè)Demo的效果圖:

iOS設(shè)備不知道現(xiàn)在有沒有可以屏幕錄制的app,這樣我就可以把操作的動(dòng)作用gif圖片po上來了,大家如果有推薦可以告訴我哈!關(guān)于拖動(dòng),長(zhǎng)按圖片后就可以將圖片拖到你想要的位置上,另外的圖片則會(huì)依次排序,很順暢的體驗(yàn)。
在使用UICollectionView的時(shí)后,我們的類需要實(shí)現(xiàn)這些協(xié)議:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,
UICollectionViewDelegate,UIGestureRecognizerDelegate。
UICollectionViewDataSource:和我們?cè)赨ITableView中所需要實(shí)現(xiàn)的UITableViewDataSource是一個(gè)道理,它里面包括以下這些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是一個(gè)專門用來管理collectionView布局的類,可以通過實(shí)現(xiàn)以下函數(shù)來調(diào)整我們界面的樣式:
@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一樣,這里就把它協(xié)議里面的的函數(shù)po出來了,通過重寫里面的函數(shù),我們可以實(shí)現(xiàn)cell的點(diǎn)擊與拖動(dòng)。
UIGestureRecognizerDelegate:由于我們還有一個(gè)拖動(dòng)的功能,所以需要實(shí)現(xiàn)用戶手勢(shì)的協(xié)議。
好了,基礎(chǔ)的概念講了,現(xiàn)在我們就開始動(dòng)手實(shí)現(xiàn)他吧!老樣子直接看源碼:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//設(shè)置背景色
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"back.jpg"]]];
//設(shè)置數(shù)據(jù)源
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 nil];
//初始化布局
self.flow = [[UICollectionViewFlowLayout alloc] init];
self.collect = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flow];
[self.collect setBackgroundColor:[UIColor clearColor]];
//注冊(cè)cell 這一步必須要實(shí)現(xiàn)
[self.collect registerClass:[CustomCollectionCell class] forCellWithReuseIdentifier:@"CustomCell"];
self.collect.delegate = self;
self.collect.dataSource = self;
[self.collect setFrame:self.view.bounds];
//添加長(zhǎng)按手勢(shì)
self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] init];
[self.longPressGestureRecognizer addTarget:self action:@selector(handleLongPressRecognizer:)];
[self.collect addGestureRecognizer:self.longPressGestureRecognizer];
[self.view addSubview:self.collect];
}
在viewDidLoad函數(shù)中,初始化了一個(gè)UICollectionViewFlowLayout布局,并且需要配合UICollectionView來使用,兩者加一起來使用才能“完美”,想比UITableView 中Cell使用的不同,在UICollectionView中必須先對(duì)Cell進(jìn)行注冊(cè)(RegisterClass),不然會(huì)在運(yùn)行過程中報(bào)錯(cuò)。如何使排列的圖片可以拖動(dòng)呢,在這里我為UICollectionView添加了一個(gè)長(zhǎng)按手勢(shì)UILongPressGestureRecognizer。當(dāng)我們長(zhǎng)按時(shí)會(huì)觸發(fā)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中展示的圖片會(huì)根據(jù)自身圖片的大小進(jìn)行按比例縮放,這樣我們的桌面看上去就會(huì)有橫版圖片與豎版圖片,如果不自定義的話就都是方方正正的九宮格,還是花點(diǎn)心思自定義一下顯示效果吧!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
以上這些就是構(gòu)成該Demo的重要組成部分了,UICollectionView還有很多的要素在這里面沒有講到,往后我還會(huì)再研究這個(gè)控件更加高級(jí)的的使用,本篇就好比是餐前的開胃小菜吧,希望大家喜歡。附上這個(gè)例子的源碼:
@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.
//設(shè)置背景色
[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"back.jpg"]]];
//設(shè)置數(shù)據(jù)源
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 nil];
//初始化布局
self.flow = [[UICollectionViewFlowLayout alloc] init];
self.collect = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flow];
[self.collect setBackgroundColor:[UIColor clearColor]];
//注冊(cè)cell 這一步必須要實(shí)現(xiàn)
[self.collect registerClass:[CustomCollectionCell class] forCellWithReuseIdentifier:@"CustomCell"];
self.collect.delegate = self;
self.collect.dataSource = self;
[self.collect setFrame:self.view.bounds];
//添加長(zhǎng)按手勢(shì)
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;
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- iOS UICollectionView刷新時(shí)閃屏的解決方法
- iOS 通過collectionView實(shí)現(xiàn)照片刪除功能
- iOS中關(guān)于Swift UICollectionView橫向分頁的問題
- iOS自定義UICollectionViewLayout實(shí)現(xiàn)瀑布流布局
- IOS collectionViewCell防止復(fù)用的兩種方法
- iOScollectionView廣告無限滾動(dòng)實(shí)例(Swift實(shí)現(xiàn))
- iOS自定義collectionView實(shí)現(xiàn)毛玻璃效果
- IOS簡(jiǎn)單實(shí)現(xiàn)瀑布流UICollectionView
- ios的collection控件的自定義布局實(shí)現(xiàn)與設(shè)計(jì)
相關(guān)文章
iOS 超級(jí)簽名之描述文件的實(shí)現(xiàn)過程
這篇文章主要介紹了iOS 超級(jí)簽名實(shí)現(xiàn)之描述文件的實(shí)現(xiàn)過程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02
IOS中(Xcode) DEBUG模式(RELEASE模式)控制NSLog輸出,NSLog輸出方式
這篇文章主要介紹了IOS中(Xcode) DEBUG模式(RELEASE模式)控制NSLog輸出,NSLog輸出方式的相關(guān)資料,需要的朋友可以參考下2016-11-11
iOS 使用 socket 實(shí)現(xiàn)即時(shí)通信示例(非第三方庫)
這篇文章主要介紹了iOS 使用 socket 即時(shí)通信示例(非第三方庫)的資料,這里整理了詳細(xì)的代碼,有需要的小伙伴可以參考下。2017-02-02
IOS 靜態(tài)庫打包流程簡(jiǎn)化詳細(xì)介紹
iOS粒子路徑移動(dòng)效果 iOS實(shí)現(xiàn)QQ拖動(dòng)效果
iOS實(shí)現(xiàn)循環(huán)滾動(dòng)公告欄

