在 UICollectionViewController 中,若要同時顯示區段頁眉與頁腳,需要設定 UICollectionViewFlowLayout 的 headerReferenceSize 與 footerReferenceSize,並註冊對應的 supplementary view。
可在初始化時建立 flowLayout,設定 itemSize、sectionInset,並保留 header 與 footer 的空間。
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; flowLayout.itemSize = CGSizeMake(ITEMWIDTH, ITEMHEIGHT); flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10); flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 200); flowLayout.footerReferenceSize = CGSizeMake(SCREEN_WIDTH, 200);
在 viewDidLoad 中註冊 cell、header 與 footer。注意 footer 要使用 UICollectionElementKindSectionFooter,而不是 SectionHeader。
[self.collectionView registerClass:[FirstHeaderReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"]; [self.collectionView registerClass:[FirstFooterReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
實作 viewForSupplementaryElementOfKind:atIndexPath: 時,依 kind 判斷要 dequeue header 還是 footer,並回傳對應的 reusable view。