Removing empty space, if the section header is hidden in the UICollectionView

后端 未结 5 2105
無奈伤痛
無奈伤痛 2020-12-13 08:57

I have two sections in UICollectionView. I want to show a section header in UICollectionView for only 1st section. Not in 0th section.

So I

5条回答
  •  伪装坚强ぢ
    2020-12-13 09:30

    Documentation clearly says -

    Return Value

    A configured supplementary view object. You must not return nil from this method.

    So you need follow -

    This method must always return a valid view object. If you do not want a supplementary view in a particular case, your layout object should not create the attributes for that view. Alternatively, you can hide views by setting the hidden property of the corresponding attributes to YES or set the alpha property of the attributes to 0. To hide header and footer views in a flow layout, you can also set the width and height of those views to 0.

    Coming to your code, below snippet should work for you:

    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionReusableView *sectionHeader = nil;
        if (kind == UICollectionElementKindSectionHeader) {
            sectionHeader = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"EventSectionHeader" forIndexPath:indexPath];
    
            if(indexPath.section == 1)
              {
                 sectionHeader.layer.borderWidth = .5f;
                 sectionHeader.layer.borderColor = [UIColor colorWithRed:221.0 / 255.0 green:223.0 / 255.0 blue:220.0 / 255.0 alpha:1.0].CGColor;
              }
            else
            {
              sectionHeader.frame = CGRectZero;
              sectionHeader.hidden = YES;
            }
        }
    
        return sectionHeader;
    }
    

提交回复
热议问题