header和footer是視圖流布局的補充。預設情況下,這些視圖是在流布局中禁用的。不過可以通過下面幾件事情來配置header和footer視圖:
一、拖拽collectionview,並進行相關設定
到Storyboard中,選擇collection view controller中的”Collection View”。在Attributes inspector中,選擇”Section Header”和”Section Footer”,一旦選中你就會在看到collection 展示出了他的Header和他的Footer.B7A4A035-9845-47E3-B2EF-0E392E884841
在header和footer之間預設為空白,我們會用storyboard來設計檢視。頭部是專門用來顯示一個部分的標題,而底部視圖只顯示靜態橫幅圖片。
二、實現viewForSupplementaryElementOfKind方法
如果你嘗試運行應用程式,你可能不會看到header和footer,這是因為我們還沒有實現”viewFOrSupplementaryElementOfKind:”方法。
代碼如下:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableview = nil;
if (kind == UICollectionElementKindSectionHeader){
UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
reusableview = headerView;
}
if (kind == UICollectionElementKindSectionFooter){
UICollectionReusableView *footerview = [collectionView dequeueResuableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];
reusableview = footerview;
}
return reusableview;
}
上面的代碼告訴它頁首/頁尾視圖應該在每個部分中使用collect view。我們首先確定該集合視圖要求header或footer view。這可以通過使用一種變數來完成。對於頭來看,我們出列header view(使用dequeueReusableSupplementaryViewOfKind :方法),並設定適當的標題和映像。正如你可以從兩個if之間的代碼,我們使用我們之前分配給獲得header/footer view標識符。