UICollectionView: How to get the header view for a section?

前端 未结 4 1980
臣服心动
臣服心动 2021-01-31 09:15

There is a method to get a cell by indexPath (UICollectionView cellForItemAtIndexPath:). But I can\"t find a method to get one of the supplementary vie

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 09:31

    First thing you have to do is check the box "Section Header" in the collection view's attribute inspector. Then add a collection reusable view just like you added your cell to the collection view, write an identifier and make a class for it if you need to. Then implement the method:

    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    

    From there do exactly like you did with cellForItemAtIndexPath Its also important to specify if its a header or footer you are coding about:

    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        Header *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerTitle" forIndexPath:indexPath];
        //modify your header
        return header;
    }
    
    else
    {
    
        EntrySelectionFooter *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"entryFooter" forIndexPath:indexPath];
        //modify your footer
        return footer;
    }
    

    use indexpath.section to know what section this is in also note that Header and EntrySelectionFooter are custom subclasses of UICollectionReusableView that I made

提交回复
热议问题