源碼下載
CollectionView的用法
- CollectionView必須在創(chuàng)建的時候就布局
- CollectionViewCell必須注冊,不能通過alloc,init創(chuàng)建,并且由CollectionView的布局決定位置和尺寸
- 不要通過
minimumInteritemSpacing
來設(shè)置cell的間距,因為設(shè)置不準(zhǔn)確,最小只能為80
如果需要自定義布局的話,只需要自定義一個UICollectionViewFlowLayout
類并且了解以下5個方法即可
// 什么時候調(diào)用:每次collectionView布局都會調(diào)用這個方法,每次collectionView刷新數(shù)據(jù)也會調(diào)用
// 一般情況下,只會調(diào)用一次
// 作用:計算所有cell的尺寸,前提條件,cell的位置固定的時候才在這計算.
// 注意:必須要調(diào)用[super prepareLayout]
- (void)prepareLayout
{
[super prepareLayout];
}
// UICollectionViewLayoutAttributes:描述cell的布局
// 每一個cell 對應(yīng) UICollectionViewLayoutAttributes,記錄frame,center,transform等等
// 返回所有cell的布局,可以一次性返回,也可以隨著用戶滾動,返回對應(yīng)cell的布局
// rect:collectionView中某個范圍
// 作用:給定一個區(qū)域,就會返回這個區(qū)域內(nèi)所有cell對應(yīng)的布局對象
// 確定cell布局
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
return nil;
}
// 是否允許當(dāng)滾動屏幕刷新布局
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
// 作用:返回collectionView最終滾動偏移量
// 調(diào)用時刻:用戶拖動的時候,手指離開就會調(diào)用
// proposedContentOffset:就是最終滾動偏移量
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
CGPoint targetP = [super targetContentOffsetForProposedContentOffset:proposedContentOffset withScrollingVelocity:velocity];
}
// 返回collectionView內(nèi)容尺寸
- (CGSize)collectionViewContentSize
{
return [super collectionViewContentSize];
}
接下來看一下使用CollectionView寫的一個小例子
具體如何創(chuàng)建CollectionView可以看下源碼,這里不細(xì)說,主要講下如何布局和定位
- 通過重寫
layoutAttributesForElementsInRect:
來獲得給定區(qū)域內(nèi)的cell的布局,在這個方法里可以改變cell的比例- 通過
rect
來取得對應(yīng)cell的布局
- 通過
NSArray *array = [super layoutAttributesForElementsInRect:rect];
- 然后遍歷
array
,來獲取cell離中心點的距離
CGFloat delta = fabs(att.center.x - offset - collectionW * 0.5);```
- 通過```CGAffineTransformMakeScale```方法來完成改變比例動畫
- 通過重寫```targetContentOffsetForProposedContentOffset:```來完成cell的定位
- 也是先取出cell的布局
NSArray *attrs = [super layoutAttributesForElementsInRect:targetRect];
- 然后遍歷```array```來獲取離中心點最近的間距值
- 這里會有個小Bug,```proposedContentOffset.x```有可能會等于-0,只需要判斷下```proposedContentOffset.x```小于0時重新將```proposedContentOffset.x```賦值為0
還在學(xué)習(xí)中,若有錯誤請指出,謝謝!!