Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UICollectionViewCell fit its subviews (using Auto Layout)

How can I change the size of a UICollectionViewCell based on the size of its subviews, using Auto Layout?

My UICollectionViewCells each only have one view in their contentView. This is a custom UIView subclass of mine that automatically resizes itself to fit all its subviews using Auto Layout. It also implements -intrinsicContentSize correctly. However the UICollectionView, or rather its layout, do not seem to care about this.

I am using a UICollectionViewFlowLayout, and tried:

  • Leaving the itemSize at its default value. This gives me cells with a size of 50 x 50.
  • Implementing the delegate method -collectionView:layout:sizeForItemAtIndexPath:. However, when this method gets called, the cells (obviously) have not appeared on screen yet, and have not been updated by the Auto Layout system.

Is there any way to change my cells' size based on their subviews using the standard Apple classes? Or do I have to implement my own UICollectionViewLayout subclass, or something else?

like image 861
fabian789 Avatar asked Aug 30 '13 07:08

fabian789


1 Answers

Have you tried this :

[self.view layoutIfNeeded];
[UIView animateWithDuration:0.5 animations:^{
     constraintConstantForWidth.constant = subviews.size.width;
     constraintConstantForHeight.constant = subviews.size.height;
     [self.view layoutIfNeeded];
}];

and make the priority of the constraint (low = 250)

I think that this issue we can handle by the constraint constant replacement.

like image 184
Akshar Darji Avatar answered Nov 15 '22 12:11

Akshar Darji