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

前端 未结 4 1977
臣服心动
臣服心动 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:41

    I would like to share my insight of the solution provided by rob mayoff but I can't post comment so I am putting it here:

    For every one of you that tried to keep reference of the supplementary views being used by a collection view but who run into issues of loosing track too early because of

    collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:
    

    being called too many times, try using an NSMapTable instead of a dictionary.

    I use

    @property (nonatomic, strong, readonly) NSMapTable *visibleCollectionReusableHeaderViews;
    

    created like this:

    _visibleCollectionReusableHeaderViews = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableWeakMemory];
    

    so that when you are keeping a reference to a supplementary view:

    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    {
        // ( ... )
        [_visibleCollectionReusableHeaderViews setObject:cell forKey:indexPath];
    

    it keeps only a WEAK reference to it in the NSMapTable and it keeps it AS LONG AS the object is not deallocated!

    You don't need anymore to remove the view from

    collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:
    

    as the NSMapTable will lose the entry as soon as the view is deallocated.

提交回复
热议问题