一、UICollectionHeaderView的作用
在使用UICollectionViewController時, 會經常使用到UICollectionHeaderView, 它是UICollectionView的一種特殊的區頭視圖,用於顯示區頭內容。
在實際開發中, 可以利用UICollectionHeaderView實現一些突出的效果, 比如插入一個廣告條、置頂一個重要的導航等。
二、UICollectionHeaderView的使用方法
UICollectionHeaderView的使用是比較簡單的:
首先要自定義一個View,繼承於UICollectionReusableView, 並實現其中的初始化函數。
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//TODO: Initialization code
}
return self;
}
在UICollectionView中,可以通過註冊區頭視圖的方法註冊此View。
[self.collectionView registerClass:[CustomHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERVIEWIDENTIFIER];
或者在Interface Builder中設置UICollectionView的Header的自定義class, 然後在自定義View中實現渲染和自定義視圖的方法。
三、UICollectionHeaderView的懸停效果實現方法
當UICollectionHeaderView出現時如果不希望它隨CollectionView一起滾動, 而希望它固定在頂部, 並且隨着滾動,不斷更新headerView的位置和狀態, 這種實現稱為懸停效果。
實現這種懸停效果的主要思路:在CollectionView滾動的時候,監聽當前滾動的偏移量,然後根據偏移量,計算當前headerView需要達到的位置,從而進行動態的變化。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//獲取當前headerView的frame
CGRect headerFrame = self.headerView.frame;
//如果headerView還處於CollectionView的頂部
if (scrollView.contentOffset.y <= -headerFrame.size.height) {
headerFrame.origin.y = scrollView.contentOffset.y;
self.headerView.frame = headerFrame;
}
//如果headerView離開了CollectionView的頂部
else {
headerFrame.origin.y = MAX(-scrollView.contentOffset.y-headerFrame.size.height, -headerFrame.size.height);
self.headerView.frame = headerFrame;
}
}
四、UICollectionHeaderView的重複利用
由於UICollectionHeaderView可能存在多個,因此對headerView的重用是必要的。由於要重複利用,我們可以使用iOS的默認重複利用機制,即buffer pool。
UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERVIEWIDENTIFIER forIndexPath:indexPath];
在調用dequeueReusableSupplementaryViewOfKind時,系統會在buffer pool中尋找與HEADERVIEWIDENTIFIER一樣的headerView,如果找不到則會使用HEADERVIEWIDENTIFIER註冊的headerView進行新的創建。如果有則系統會返回重複利用的headerView。
五、UICollectionHeaderView的動畫特效實現
UICollectionHeaderView還能夠實現一些動畫特效,比如拉伸動畫、放大動畫等,讓CollectionView看起來更加生動。
實現這些動畫特效的關鍵步驟是:在CollectionView滾動的時候,監聽當前滾動的偏移量,然後根據偏移量計算出需要展示的動畫效果(UIView的transform動畫EQ)。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat yOffset = scrollView.contentOffset.y;
if (yOffset < 0) {
CGFloat factor = MAX(ABS(yOffset/header_height), 0.0001);
CGFloat f = (header_height*yOffset+header_height)/header_height;
CGAffineTransform t = CGAffineTransformMakeScale(f, f);
self.headerView.imageView.transform = t;
}
}
六、UICollectionHeaderView的優化
當數據量過大時,headerView的重複利用效率會下降,這時需要進行優化措施。
優化措施:使用離屏渲染,將常用的元素(比如label、imageView等)預先緩存,少做計算即可。
七、總結
UICollectionHeaderView的懸停、動畫特效等實現方法都是圍繞着監聽當前CollectionView的offset來進行的,對headerView的重複利用和離屏渲染的優化也是需要注意的。在實際項目中,我們可以將上述方法綜合運用,讓UICollectionHeaderView展現更加豐富的效果。
原創文章,作者:BOTJL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/329199.html