你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 運用iOS控件UICollectionView生成可拖動的桌面的實例

運用iOS控件UICollectionView生成可拖動的桌面的實例

編輯:IOS開發綜合

一個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 = CGAff.netransformMakeScale(2.0f, 2.0f); 
//  }]; 
} 
 
//減少效果 
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{ 
//  CustomCollectionCell * cell = (CustomCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath]; 
//   
//  [UIView animateWithDuration:1 animations:^{ 
//    cell.transform = CGAff.netransformMakeScale(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; 
} 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持本站。

【運用iOS控件UICollectionView生成可拖動的桌面的實例】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved