UICollectionView autosize height

前端 未结 9 1676
孤城傲影
孤城傲影 2020-12-04 07:02

How do I properly resize a UICollectionView so that it fully displays its contents? I have tried many things, including setting its frame, calling reloadData an

相关标签:
9条回答
  • 2020-12-04 07:36

    For me it is even simpler I think

    -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    
    {
    //add following code line after adding cells, before Return
    ...........
    .........
    scrollView.contentSize = = collectionView.contentSize;
    
    //now scrollView size is equal to collectionView size. No matter how small or big it is.
    
    return cell;
    }
    
    0 讨论(0)
  • 2020-12-04 07:38

    I solved this eventually by fixing all Auto Layout issues, fixing the height of the collection view using a constraint. Then, whenever I know the content has changed I update the value of the constraint using the value collectionView.contentSize.height:

    self.verticalLayoutConstraint.constant = self.collectionView.contentSize.height;
    

    Then the collection view is resized properly and it behaves nicely within the overall scrollview. I have updated the GitHub test project with my changes.

    To me, doing this by updating the constraint manually instead of being able to tell iOS: "make the frame height of the collection view as large as needed" does not feel right to me, but it's the best I have come up with so far. Please post a better answer if you have one.

    0 讨论(0)
  • 2020-12-04 07:45

    The simplest method I found is to override sizeThatFits: methods as is:

    - (CGSize)sizeThatFits:(CGSize)size
    {
        if( self.superview )
            [self.superview layoutIfNeeded]; // to force evaluate the real layout
    
        return self.collectionViewLayout.collectionViewContentSize;
    }
    
    0 讨论(0)
提交回复
热议问题