Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-sizing UICollectionView headers

I'm trying to make a detail screen for a to-do list kind of app. Here's what the detail screen currently looks like:

detail screen

This is a UICollectionViewController, with a header. The header contains 2 UILabel objects, and a UITextView object. The layout of these objects is managed by a vertical UIStackView. A UIView is used to set a white background.

I'm having some difficulties in defining the height of this UICollectionReusableView at runtime. Any advice is appreciated.

like image 944
Kelvin Lau Avatar asked Aug 29 '16 08:08

Kelvin Lau


Video Answer


1 Answers

This is a bit of a hack, but seems to work.

    // showhere to keep a reference
    UICollectionReusableView * _cachedHeaderView;


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

        if(!_cachedHeaderView){
            // dequeue the cell from storyboard
            _cachedHeaderView = 
         [collectionView dequeueReusableCellWithReuseIdentifier:@"header_cell" 
                                                   forIndexPath:indexPath];

            // set captions/images on the header etc...

            // tell the collectionview to redraw this section
          [self.collectionView reloadSections:[NSIndexSet 
                            indexSetWithIndex:indexPath.section]];
        }

        return _cachedHeaderView;
    }


        - (CGSize)collectionView:(UICollectionView *)collectionView 
                          layout:(UICollectionViewLayout*)collectionViewLayout        
 referenceSizeForHeaderInSection:(NSInteger)section{

        // once there is a reference ot the view, use it to figure out the height
        if(_cachedHeaderView){
            CGSize size = 
[_cachedHeaderView systemLayoutSizeFittingSize:collectionView.bounds.size 
                 withHorizontalFittingPriority:UILayoutPriorityRequired 
                       verticalFittingPriority:UILayoutPriorityDefaultLow];
            return size;

        }

        // a placeholder value just to get the dequeueReusableCellWithReuseIdentifier to work 
        return CGSizeMake(collectionView.bounds.size.width, 100);
    }

like image 186
Friggles Avatar answered Oct 11 '22 05:10

Friggles