使用iOS控制項UICollectionView產生可拖動的案頭的執行個體_IOS

來源:互聯網
上載者:User

一個App受歡迎的程度,一方面來源於它本身為使用者提供便捷的功能,另一方面則來源於它的UI。UI是使用者體驗重要的組成部分,構成UI的的元素恰恰離不開那些看似獨立的控制項。在開發的過程中,大家對UITableView應該很熟悉吧!確實UITableView在處理資料顯示方面有著很強大的功能,例如網紅們使用的微博,微信社交軟體的聊天介面等等,這種流式布局使用UITableView簡直最合適不過了;但畢竟UITableView不是萬能的,當需要顯示橫縱向的資料時它就顯得捉襟見肘了,雖然這也難不倒我們程式猿但是何必要大費周章的去定義複雜的cell呢!UICollectionView就是專門用來應付這種布局的,使用UICollectionView可以給我們帶來以下幾點優勢:1.可以高度的定製內容展示的樣式 2.高效的管理大量的資料。

首先給大家看一下這個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 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 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; } 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.