In a CollectionView
, some cells should have an additional subview or layer. The CollectionView
can be told to resize it's cells, thus all content needs to resize appropriately.
Currently, the cell is initialized from a nib containing a cell with imageview; the cell nib is linked to a custom UICollectionViewCell
subclass, that only does the init. Autoresize subviews is checked.
The CollectionView
is told to resize the cell by a value derived and returned in sizeForItemAtIndexPath:
. I have subclassed a FlowLayout but it only specifies ScrollDirection
and Insets
.
All of that is working fine. Problem: How do I add subview/layer to the cell so it also resizes correctly? I tried adding subviews and layers with translatesAutoresizingMaskIntoConstraints
off, but these do not automatically change size at all. Also tried to use code frame/view instead of nib.
The best I got now is a cell.contentView.layer
sublayer which I add in cellForItemAtIndexPath:
; that is "manually" resized by storing the cell's frame.size
from sizeForItemAtIndexPath:
, which is not only ugly but also ends up with the sublayer having various sizes for different cells.
Any help appreciated!
I ran into the same issue just now.
When using the UICollectionViewFlowLayoutDelegate method to set the cell size depending on device and device-orientation, the size would be calculated properly but subviews would not resize to fill the newly size cell. The effect was a large blank cell with small subviews that don't fill the cell's bounds / remain the size equal to their current value in the xib file.
I solved this by doing the following in
awakeFromNib
:Prior to doing this, the contentView mask was
nil
.This worked for me.. This code goes inside of your subclassed UICollectionViewCell.swift file (where your code involving the custom cell is located)
Swift solution*
A simple auto layout solution is to set constraints to the container view.
So if we have an image view with a parent view, we basically want to tell the subview (the image view) to maintain a leading, trailing, bottom, and top space distance of 0 to the container view.
I always prefer autolayout when possible. But Sometimes usings frames and bounds just is a timesaver when a view is determined straightforward by only its superview.
In the case of UICollectionViewCell I set an image to be the cells frame +
self.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
But when I had different sizes of cells in the collectionView it messed up things and the image sometimes took the size of a different cell.
So I turned to working with the the cells bounds and - ye that acually worked out fine.
So maybe give that a try?