天天看點

iOS開發筆記--iOS7中彈簧式清單的制作

這是我的WWDC2013系列筆記中的一篇,完整的筆記清單請參看這篇總覽。本文僅作為個人記錄使用,也歡迎在許可協定範圍内轉載或使用,但是還煩請保留原文連結,謝謝您的了解合作。如果您覺得本站對您能有幫助,您可以使用RSS或郵件方式訂閱本站,這樣您将能在第一時間擷取本站資訊。

本文涉及到的WWDC2013 Session有

  • Session 206 Getting Started with UIKit Dynamics
  • Session 217 Exploring Scroll Views in iOS7

UIScrollView可以說是UIKit中最重要的類之一了,包括UITableView和UICollectionView等重要的資料容器類都是UIScrollView的子類。在曆年的WWDC上,UIScrollView和相關的API都有專門的主題進行介紹,也可以看出這個類的使用和變化之快。今年也不例外,因為iOS7完全重新定義了UI,這使得UIScrollView裡原來不太會使用的一些用法和實作的效果在新的系統中得到了很好的表現。另外,由于引入了UIKit Dynamics,我們還可以結合ScrollView做出一些以前不太可能或者需要花費很大力氣來實作的效果,包括帶有重力的swipe或者是類似新的資訊app中的帶有彈簧效果聊天泡泡等。如果您還不太了解iOS7中資訊app的效果,這裡有一張gif圖可以幫您大概了解一下:

iOS開發筆記--iOS7中彈簧式清單的制作

這次筆記的内容主要就是實作一個這樣的效果。為了避免重複造輪子,我對這個效果進行了一些簡單的封裝,并連同這篇筆記的demo一起扔在了Github上,有需要的童鞋可以到這裡自取。

iOS7的SDK中Apple最大的野心其實是想用SpriteKit來結束iOS平台遊戲開發(至少是2D遊戲開發)的亂戰,統一遊戲開發的方式并建立良性社群。而UIKit Dynamics,個人猜測Apple在花費力氣為SpriteKit開發了實體引擎的同時,發現在UIKit中也可以使用,并能得到不錯的效果,于是順便革新了一下設計理念,在UI設計中引入了不少實體的概念。在iOS系統中,最為典型的應用是鎖屏界面打開相機時中途放棄後的重力下墜+反彈的效果,另一個就是資訊應用中的加入彈性的消息清單了。彈性清單在我自己上手試過以後覺得表現形式确實很生動,可以消除原來清單那種冷冰冰的感覺,是有可能在今後的設計中被大量使用的,是以決定學上一學。

首先我們需要知道要如何實作這樣一種效果,我們會用到哪些東西。毋庸置疑,如果不使用UIKit Dynamics的話,自己從頭開始來完成會是一件非常費力的事情,你可能需要實作一套位置計算和實體模拟來使效果看起來真實滑潤。而UIKit Dynamics中已經給我們提供了現成的彈簧效果,可以用

UIAttachmentBehavior

進行實作。另外,在說到彈性效果的時候,我們其實是在描述一個清單中的各個cell之間的關系,對于傳統的UITableView來說,描述UITableViewCell之間的關系是比較複雜的(因為Apple已經把絕大多數工作做了,包括計算cell位置和位移等。使用越簡單,定制就會越麻煩在絕大多數情況下都是真理)。而UICollectionView則通過layout來完成cell之間位置關系的描述,給了開發者較大的空間來實作布局。另外,UIKit Dynamics為UICollectionView做了很多友善的Catagory,可以很容易地“指導”UICollectionView利用加入實體特性計算後的結果,在實作彈性效果的時候,UICollectionView是我們不二的選擇。

如果您在閱讀這篇筆記的時候遇到困難的話,建議您可以看看我之前的一些筆記,包括今年的UIKit Dynamics的介紹和去年的UICollectionView介紹。

話不多說,我們開工。首先準備一個UICollectionViewFlowLayout的子類(在這裡叫做

VVSpringCollectionViewFlowLayout

),然後在ViewController中用這個layout實作一個簡單的collectionView:

[objc]  view plain  copy  

iOS開發筆記--iOS7中彈簧式清單的制作
iOS開發筆記--iOS7中彈簧式清單的制作
  1. //ViewController.m  
  2. @interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>  
  3. @property (nonatomic, strong) VVSpringCollectionViewFlowLayout *layout;  
  4. @end  
  5. static NSString *reuseId = @"collectionViewCellReuseId";  
  6. @implementation ViewController  
  7. - (void)viewDidLoad  
  8. {  
  9.     [super viewDidLoad];  
  10.   // Do any additional setup after loading the view, typically from a nib.  
  11.   self.layout = [[VVSpringCollectionViewFlowLayout alloc] init];  
  12.     self.layout.itemSize = CGSizeMake(self.view.frame.size.width, 44);  
  13.     UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:self.layout];  
  14.     collectionView.backgroundColor = [UIColor clearColor];  
  15.     [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseId];  
  16.     collectionView.dataSource = self;  
  17.     [self.view insertSubview:collectionView atIndex:0];  
  18. }  
  19. #pragma mark - UICollectionViewDataSource  
  20. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section  
  21. {  
  22.     return 50;  
  23. }  
  24. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath  
  25. {  
  26.     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseId forIndexPath:indexPath];  
  27.     //Just give a random color to the cell. See https://gist.github.com/kylefox/1689973  
  28.     cell.contentView.backgroundColor = [UIColor randomColor];  
  29.     return cell;  
  30. }  
  31. @end  

這部分沒什麼可以多說的,現在我們有一個标準的FlowLayout的UICollectionView了。通過使用UICollectionViewFlowLayout的子類來作為開始的layout,我們可以節省下所有的初始cell位置計算的代碼,在上面代碼的情況下,這個collectionView的表現和一個普通的tableView并沒有太大不同。接下來我們着重來看看要如何實作彈性的layout。對于彈性效果,我們需要的是連接配接一個item和一個錨點間彈性連接配接的

UIAttachmentBehavior

,并能在滾動時設定新的錨點位置。我們在scroll的時候,隻要使用UIKit Dynamics的計算結果,替代掉原來的位置更新計算(其實就是簡單的scrollView的contentOffset的改變),就可以模拟出彈性的效果了。

首先在

-prepareLayout

中為cell添加

UIAttachmentBehavior

[objc]  view plain  copy  

iOS開發筆記--iOS7中彈簧式清單的制作
iOS開發筆記--iOS7中彈簧式清單的制作
  1. //VVSpringCollectionViewFlowLayout.m  
  2. @interface VVSpringCollectionViewFlowLayout()  
  3. @property (nonatomic, strong) UIDynamicAnimator *animator;  
  4. @end  
  5. @implementation VVSpringCollectionViewFlowLayout  
  6. //...  
  7. -(void)prepareLayout {  
  8.     [super prepareLayout];  
  9.     if (!_animator) {  
  10.         _animator = [[UIDynamicAnimator alloc] initWithCollectionViewLayout:self];  
  11.         CGSize contentSize = [self collectionViewContentSize];  
  12.         NSArray *items = [super layoutAttributesForElementsInRect:CGRectMake(0, 0, contentSize.width, contentSize.height)];  
  13.         for (UICollectionViewLayoutAttributes *item in items) {  
  14.             UIAttachmentBehavior *spring = [[UIAttachmentBehavior alloc] initWithItem:item attachedToAnchor:item.center];  
  15.             spring.length = 0;  
  16.             spring.damping = 0.5;  
  17.             spring.frequency = 0.8;  
  18.             [_animator addBehavior:spring];  
  19.         }  
  20.     }  
  21. }  
  22. @end  

prepareLayout将在CollectionView進行排版的時候被調用。首先當然是call一下super的prepareLayout,你肯定不會想要全都要自己進行設定的。接下來,如果是第一次調用這個方法的話,先初始化一個UIDynamicAnimator執行個體,來負責之後的動畫效果。iOS7 SDK中,UIDynamicAnimator類專門有一個針對UICollectionView的Category,以使UICollectionView能夠輕易地利用UIKit Dynamics的結果。在

UIDynamicAnimator.h

中能夠找到這個Category:

[objc]  view plain  copy  

iOS開發筆記--iOS7中彈簧式清單的制作
iOS開發筆記--iOS7中彈簧式清單的制作
  1. @interface UIDynamicAnimator (UICollectionViewAdditions)  
  2. // When you initialize a dynamic animator with this method, you should only associate collection view layout attributes with your behaviors.  
  3. // The animator will employ thecollection view layout’s content size coordinate system.  
  4. - (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout*)layout;  
  5. // The three convenience methods returning layout attributes (if associated to behaviors in the animator) if the animator was configured with collection view layout  
  6. - (UICollectionViewLayoutAttributes*)layoutAttributesForCellAtIndexPath:(NSIndexPath*)indexPath;  
  7. - (UICollectionViewLayoutAttributes*)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;  
  8. - (UICollectionViewLayoutAttributes*)layoutAttributesForDecorationViewOfKind:(NSString*)decorationViewKind atIndexPath:(NSIndexPath *)indexPath;  
  9. @end  

于是通過

-initWithCollectionViewLayout:

進行初始化後,這個UIDynamicAnimator執行個體便和我們的layout進行了綁定,之後這個layout對應的attributes都應該由綁定的UIDynamicAnimator的執行個體給出。就像下面這樣:

[objc]  view plain  copy  

iOS開發筆記--iOS7中彈簧式清單的制作
iOS開發筆記--iOS7中彈簧式清單的制作
  1. //VVSpringCollectionViewFlowLayout.m  
  2. @implementation VVSpringCollectionViewFlowLayout  
  3. //...  
  4. -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {  
  5.     return [_animator itemsInRect:rect];  
  6. }  
  7. -(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {  
  8.     return [_animator layoutAttributesForCellAtIndexPath:indexPath];  
  9. }  
  10. @end  

讓我們回到

-prepareLayout

方法中,在建立了UIDynamicAnimator執行個體後,我們對于這個layout中的每個attributes對應的點,都建立并添加一個添加一個

UIAttachmentBehavior

(在iOS7 SDK中,UICollectionViewLayoutAttributes已經實作了UIDynamicItem接口,可以直接參與UIKit Dynamic的計算中去)。建立時我們希望collectionView的每個cell就保持在原位,是以我們設定了錨點為目前attribute本身的center。

接下來我們考慮滑動時的彈性效果的實作。在系統的資訊app中,我們可以看到彈性效果有兩個特點:

  • 随着滑動的速度增大,初始的拉伸和壓縮的幅度将變大
  • 随着cell距離螢幕觸摸位置越遠,拉伸和壓縮的幅度

對于考慮到這兩方面的特點,我們所期望的滑動時的各cell錨點的變化應該是類似這樣的:

iOS開發筆記--iOS7中彈簧式清單的制作

現在我們來實作這個錨點的變化。既然都是滑動,我們是不是可以考慮在UIScrollView的

–scrollViewDidScroll:

委托方法中來設定新的Behavior錨點值呢?理論上來說當然是可以的,但是如果這樣的話我們大概就不得不面臨着将剛才的layout執行個體設定為collectionView的delegate這樣一個事實。但是我們都知道layout應該做的事情是給collectionView提供必要的布局資訊,而不應該負責去處理它的委托事件。處理collectionView的回調更恰當地應該由處于collectionView的controller層級的類來完成,而不應該由一個給collectionView提供資料和資訊的類來響應。在

UICollectionViewLayout

中,我們有一個叫做

-shouldInvalidateLayoutForBoundsChange:

的方法,每次layout的bounds發生變化的時候,collectionView都會詢問這個方法是否需要為這個新的邊界和更新layout。一般情況下隻要layout沒有根據邊界不同而發生變化的話,這個方法直接不做處理地傳回NO,表示保持現在的layout即可,而每次bounds改變時這個方法都會被調用的特點正好可以滿足我們更新錨點的需求,是以我們可以在這裡面完成錨點的更新。

[objc]  view plain  copy  

iOS開發筆記--iOS7中彈簧式清單的制作
iOS開發筆記--iOS7中彈簧式清單的制作
  1. //VVSpringCollectionViewFlowLayout.m  
  2. @implementation VVSpringCollectionViewFlowLayout  
  3. //...  
  4. -(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {  
  5.     UIScrollView *scrollView = self.collectionView;  
  6.     CGFloat scrollDelta = newBounds.origin.y - scrollView.bounds.origin.y;  
  7.     //Get the touch point  
  8.     CGPoint touchLocation = [scrollView.panGestureRecognizer locationInView:scrollView];  
  9.     for (UIAttachmentBehavior *spring in _animator.behaviors) {  
  10.         CGPoint anchorPoint = spring.anchorPoint;  
  11.         CGFloat distanceFromTouch = fabsf(touchLocation.y - anchorPoint.y);  
  12.         CGFloat scrollResistance = distanceFromTouch / 500;  
  13.         UICollectionViewLayoutAttributes *item = [spring.items firstObject];  
  14.         CGPoint center = item.center;  
  15.       //In case the added value bigger than the scrollDelta, which leads an unreasonable effect  
  16.         center.y += (scrollDelta > 0) ? MIN(scrollDelta, scrollDelta * scrollResistance)  
  17.                                       : MAX(scrollDelta, scrollDelta * scrollResistance);  
  18.         item.center = center;  
  19.         [_animator updateItemUsingCurrentState:item];  
  20.     }  
  21.     return NO;  
  22. }  
  23. @end  

首先我們計算了這次scroll的距離

scrollDelta

,為了得到每個item與觸摸點的之間的距離,我們當然還需要知道觸摸點的坐标

touchLocation

。接下來,可以根據距離對每個錨點進行設定了:簡單地計算了原來錨點與觸摸點之間的距離

distanceFromTouch

,并由此計算一個系數。接下來,對于目前的item,我們擷取其目前錨點位置,然後将其根據

scrollDelta

的數值和剛才計算的系數,重新設定錨點的位置。最後我們需要告訴UIDynamicAnimator我們已經完成了對冒點的更新,現在可以開始更新實體計算,并随時準備collectionView來取LayoutAttributes的資料了。

也許你還沒有緩過神來?但是我們确實已經做完了,讓我們來看看實際的效果吧:

iOS開發筆記--iOS7中彈簧式清單的制作

當然,通過調節

damping

frequency

scrollResistance

的系數等參數,可以得到彈性不同的效果,比如更多的震蕩或者更大的幅度等等。

這個layout實作起來非常簡單,我順便封裝了一下放到了Github上,大家有需要的話可以點選這裡下載下傳并直接使用。

轉自:http://www.onevcat.com/2013/09/spring-list-like-ios7-message/