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
*override func awakeFromNib() {
super.awakeFromNib()
self.contentView.autoresizingMask.insert(.FlexibleHeight)
self.contentView.autoresizingMask.insert(.FlexibleWidth)
}
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*
@Alfie Hanssen solution (here) didn't work properly for me, according with this article:
The size of the cell view in the XIB is 50 x 50 points, which is the default size of the collection view cells as set in the flow layout. Even if it’s a bit hard to work with a cell this small in Interface Builder, it’s better to not change the default size. The problem is that Auto Layout considers the manually set size as being fixed and generates a NSAutoresizingMaskLayoutConstraint error when it tries to adjust the cells height automatically
I have inspected the UICollectionViewCell and I found that there is a view between the cell and the contentView, and that view has intrinsic width and height constraints. Instead of the AutoresizingMask I'm just updating as below and seems working for me.
override func layoutSubviews() {
contentView.superview?.frame = bounds
super.layoutSubviews()
}
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
:
- (void)awakeFromNib
{
[super awakeFromNib];
self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.contentView.translatesAutoresizingMaskIntoConstraints = YES;
}
Prior to doing this, the contentView mask was nil
.
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.