UICollectionViewFlowLayout Size Warning When Rotating Device to Landscape - ios

We are using a UICollectionView to display cell that cover the full screen (minus the status and nav bar). The cell size is set from self.collectionView.bounds.size:
- (void)viewWillAppear:(BOOL)animated
{
//
// value isn't correct with the top bars until here
//
CGSize tmpSize = self.collectionView.bounds.size;
_currentCellSize = CGSizeMake( (tmpSize.width), (tmpSize.height));
}
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return _currentCellSize;
}
This sets the correct sizing for each device. Each cell is defined to have no insets, and the layout has no header or footer. However, when we rotate from portrait to landscape we get the following "complaint":
the behavior of the UICollectionViewFlowLayout is not defined because:
the item height must be less that the height of the UICollectionView minus the section insets top and bottom values.
Now I understand this error, however we reset the size of the cell and use the flow layouts built in rotation transition:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//self.collectionView.bounds are still the last size...not the new size here
}
- (void)didRotateFromInterfaceOrientation: UIInterfaceOrientation)fromInterfaceOrientation
{
CGSize tmpSize = self.collectionView.bounds.size;
_currentCellSize = CGSizeMake( (tmpSize.width), (tmpSize.height));
[self.collectionView performBatchUpdates:nil completion:nil];//this will force the redraw/size of the cells.
}
The cells render correctly in landscape.
It seems as though the Flow Layout sees the old cell size (which causes the complaint since it will be too tall), but does read/render the new cell size set in didRotateFromInterfaceOrientation.
Is there a way to get rid of the complaint?
We've tried finding another hook during a device rotate transition that has access to the correct target screen size (vs the current screen size) with no luck. Debug output shows the complaint happens after willRotateToInterfaceOrientation but before didRotateFromInterfaceOrientation.
We've also verified the obvious; if we set up the cell height to be a fixed size less than the landscape screen height, the complaint doesn't occur. Also, the complaint does not occur when rotating from landscape back to portrait.
Everything runs fine, and renders correctly. However this complaint worries us. Anyone else have any ideas or solutions?

I was getting the same warning. Unsatisfied with the "reloadData" approach, I found that calling [self.collectionView.collectionViewFlowLayout invalidateLayout] before setting the frame of the collection view silenced the warning and yielded the expected results.

Not to throw another shrimp on this loaded, yet unaccepted, barbie.
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
[collectionView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
return CGSizeMake(100, collectionView.frame.size.height);
}
Setting the content insets just before returning the cell size did the trick for me.
Note:
I am using a container view in a storyboard to load the collection view within a UIViewController. I tried setting this on the flowLayout object in the storyboard. The collection view in the storyboard. And overriding one of the UICollectionViewDelegateFlowLayout; though I do not remember which one. I'm also not sure if this will work for a vertical layout.

In
[UIViewController willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration]
I called the, [UICollectionViewLayout invalidateLayout] and seems to work good.

I solved it.
You should just let the height of flowLayout less than collcetionView.frame.size.height.
[flowLayout setItemSize:CGSizeMake(width, height)];
collectionView.frame = CGRectMake(12, 380, 290, 80);

A lot of the solutions suggest adding invalidateLayout to willAnimateRotationToInterfaceOrientation - but this is deprecated since iOS 8.
For iOS 8 and higher, use:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[self.collectionView.collectionViewLayout invalidateLayout];
}
Thanks to #user7097242's comment here is a swift4 version:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.collectionView.collectionViewLayout.invalidateLayout()
}

I encountered this same issue. If the collection view was displayed when in portrait orientation, the cells would disappear when rotated to landscape. I did a combination of the other answers here to fix this.
I set my view (the one that contains the UICollectionView) up to receive the UIDeviceOrientationDidChangeNotification notification. In the method that responds to that notification, after the UICollectionView frame was adjusted, I did the following:
- (void)orientationChanged:(NSNotification *)notification
{
CGSize size = (CGSize){self.frame.size.width - 2*kContentMargin, self.frame.size.height - 2*kContentMargin};
[self.collectionView.collectionViewLayout setItemSize:size];
[self.collectionView.collectionViewLayout invalidateLayout];
[self.collectionView reloadData];
}
Note that the frame of the UICollectionView is being set automatically upon rotation because its resizingMask is set to this upon initialization:
self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

Just encountered and fixed the same problem. Since my solution is more along the lines you were asking for and doesn't match any existing answer, I've posted it here.
#define NUMBER_OF_CELLS_PER_ROW 1
- (UICollectionViewFlowLayout *)flowLayout {
return (UICollectionViewFlowLayout *)self.collectionViewLayout;
}
- (CGSize)itemSizeInCurrentOrientation {
CGFloat windowWidth = self.collectionView.window.bounds.size.width;
CGFloat width = (windowWidth - (self.flowLayout.minimumInteritemSpacing * (NUMBER_OF_CELLS_PER_ROW - 1)) - self.flowLayout.sectionInset.left - self.flowLayout.sectionInset.right)/NUMBER_OF_CELLS_PER_ROW;
CGFloat height = 80.0f;
return CGSizeMake(width, height);
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[self.flowLayout invalidateLayout];
self.flowLayout.itemSize = [self itemSizeInCurrentOrientation];
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
// Now that the rotation is complete, load the cells.
[self.collectionView reloadData];
}

This solved it for me:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[self.collectionView.collectionViewLayout invalidateLayout];
}
And I am using this delegate method for setting the size:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
And I can from there use this with the correct frame after rotation:
self.collectionView.frame.size

My fix was as simple as unchecking 'Adjust Scroll View Insets' for the view controller in IB, since I needed my navigation bar to be translucent.

This works for me: (and hope it also works for you!)
- (void)viewWillLayoutSubviews
{
self.flowLayout.itemSize = CGSizeMake(self.collectionView.bounds.size.width/4,self.collectionView.bounds.size.height);
[self.flowLayout invalidateLayout];
}
- (void)viewDidLayoutSubviews
{
self.flowLayout.itemSize = CGSizeMake(self.collectionView.bounds.size.width/4,self.collectionView.bounds.size.height);
}

I faced the same problem.
here is how i solved it. hope it helps
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:( NSTimeInterval)duration
{
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
[self.collectionView reloadData];
}

I ran into the same problem when resizing the frame of a UICollectionView. If I used the delegate method on FlowLayout to return the size of the cell (which would be updated based on the size of the containing UICollectionView), I would get the error message when I resized (smaller) the frame of the UICollectionView, since it didn't seem to ask the delegate for updated size information before complaining. It would eventually ask the delegate method for size info when redrawing, but it would still issue the warning at the time I assigned a new frame method. To get rid of the warning, I explicitly set the itemSize property of the UICollectionViewFlowLayout object before I set the frame to a new smaller value. My situation is simple enough that I think I can get away with doing the itemSize calculation at this point (since all my items in the collection view are the same size), instead of depending on the delegate method. Just setting the itemSize property while leaving the delegate method implemented did not solve the problem, as I think it ignored the value of itemSize if it detected that the delegate method was implemented (if it knows it is there, why doesn't it call it?!). Hopefully this helps - perhaps you can also explicitly set the itemSize before rotation.

Just to suppress warning and (probably, not sure) improve performance you could before returning size in
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
check if view controller is in process of rotation and if it is return some relatively small size like CGSizeMake(0.1, 0.1)

You can subclass UICollectionView and override setBounds:. There before calling [super setBounds:] the item size can be adjusted to the new bounds.
You should check whether the size of the bounds has changed, because setBounds: is invoked also while scrolling.

Try this...
UICollectionViewFlowLayout *layout = (id) self.collectionView.collectionViewLayout;
layout.itemSize = CGSizeMake(0.1, 0.1);
It's works for me.

Following code fixed it for me:
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return self.collectionView.frame.size;
}

I've used an UICollectionViewFlowLayoutInvalidationContext, in which I calculate the new offset such that it maintains the same content offset. My own function collectionViewSizeForOrientation: returns the proper size. Its not perfect, but at least it's not sketchy:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
CGSize fromCollectionViewSize = [self collectionViewSizeForOrientation:[self interfaceOrientation]];
CGSize toCollectionViewSize = [self collectionViewSizeForOrientation:toInterfaceOrientation];
CGFloat currentPage = [_collectionView contentOffset].x / [_collectionView bounds].size.width;
NSInteger itemCount = [_collectionView numberOfItemsInSection:0];
UICollectionViewFlowLayoutInvalidationContext *invalidationContext = [[UICollectionViewFlowLayoutInvalidationContext alloc] init];
[invalidationContext setContentSizeAdjustment:CGSizeMake(toCollectionViewSize.width * itemCount - fromCollectionViewSize.width * itemCount, toCollectionViewSize.height - fromCollectionViewSize.height)];
[invalidationContext setContentOffsetAdjustment:CGPointMake(currentPage * toCollectionViewSize.width - [_collectionView contentOffset].x, 0)];
[[_collectionView collectionViewLayout] invalidateLayoutWithContext:invalidationContext];
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}
collectionViewSizeForOrientation: in my case is the following, assuming that insets and item spacing are 0:
- (CGSize)collectionViewSizeForOrientation:(UIInterfaceOrientation)orientation
{
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
CGFloat width = UIInterfaceOrientationIsLandscape(orientation) ? MAX(screenSize.width, screenSize.height) : MIN(screenSize.width, screenSize.height);
CGFloat height = UIInterfaceOrientationIsLandscape(orientation) ? MIN(screenSize.width, screenSize.height) : MAX(screenSize.width, screenSize.height);
return CGSizeMake(width, height);
}

Trying to find a solution to silence these warnings on iOS 7 was proving difficult for me. I ended up resorting to subclassing my UICollectionView and added the following code.
- (void)setFrame:(CGRect)frame
{
if (!iOS8 && (frame.size.width != self.frame.size.width))
{
[self.collectionViewLayout invalidateLayout];
}
[super setFrame:frame];
}
Some might want to do a whole size check with CGSizeEqualToSize().

try at the end of didRotateFromInterfaceOrientation:
[self.collectionView setNeedsLayout]
if it does not work try to move all this stuff from didRotateFromInterfaceOrientation to willRotateToInterfaceOrientation

Note: In my case, I discovered that we were setting the preferredContentSize property of the UIViewController in question. If you find this to be your case, you might have to deal with the following method of the UICollectionViewDelegateFlowLayout protocol:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize size = collectionViewLayout.collectionView.bounds.size;
...
return size;
}

I know this is an old question, but I just got the same problem and spent an hour to solve it. My problem was that, it seems the UICollectionView's frame size is always wrong (the height doesn't match the container) while I set the frame size right before the UICollectionView Flow layout delegate is called. So, I set the UICollectionView frame size again on the method :
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
And that did the trick. The height is now showing correctly and the warning is gone.

Related

UICollectionViewCell sized relative to its collection-view

I have a (horizontal) collection-view, and I change its size via auto layout constraints. However, when the collection-view's size changes, the cell remains the same static size.
To demonstrate, here's the collection-view in the view debugger (I've labeled both the collectionview and one of its cells):
As you can see, the cell remains the original size and is now actually taller than its encasing collection-view.
So how can I constrain the cell to always fit within its collection-view?
If you want to resize your view you can use the following to reset the item size on rotation, this would go inside your view controller subclass.
This should be fairly efficent as it is only called when the size of the visible view controller changes.
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator;
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:({
^(id<UIViewControllerTransitionCoordinatorContext> context) {
UICollectionViewFlowLayout *layout = (id)self.collectionView.collectionViewLayout; {
CGFloat height = CGRectGetHeight(self.collectionView.bounds);
layout.itemSize = (CGSize) {
.width = height,
.height = height
};
}
[layout invalidateLayout];
};
}) completion:nil];
}
You should also check out these answers for some more solutions.
I solved this through setting the item's height and width equal to the collection-view's height. I do this in sizeForItemAtIndexPath:
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(collectionView.frame.size.height, collectionView.frame.size.height);
}
Because in my case the cell's need to be perfect squares, setting the cell's height and width to the height of the collection-view works perfectly.
Not that your class must implement the UICollectionViewDelegateFlowLayout protocol for this method to be exposed.

Size of UICollectionView is sometimes wrong

Here is my problem: I'm developing a Kodi Remote on iOS (http://forum.kodi.tv/showthread.php?tid=235973) and everything run pretty well (a classic development) but I'm having a behavior that I can't explain.
I have multiple view controllers; in one of them (a UIViewController containing a UICollectionView), I implemented this delegate method :
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize originalSize = [(UICollectionViewFlowLayout *)collectionViewLayout itemSize];
CGSize collectionViewSize = [collectionView frame].size;
CGFloat interItemSpacing = [(UICollectionViewFlowLayout *)collectionViewLayout minimumInteritemSpacing];
UICollectionViewFlowLayout *collectionViewFlowLayout = (UICollectionViewFlowLayout *)[[self collectionView] collectionViewLayout];
UIEdgeInsets sectionInset = [collectionViewFlowLayout sectionInset];
CGFloat usableWidth = (collectionViewSize.width - ((kColumns - 1) * interItemSpacing) - sectionInset.left - sectionInset.right);
CGFloat width = usableWidth / kColumns;
CGFloat height = width * originalSize.height / originalSize.width;
return CGSizeMake(width, height);
}
I get the collection view frame (bounds is the same, of course, I don't need origin) and it works great. I get on an iPhone 5 simulator 288 width for a no matter height.
BUT, in a copy-paste of the view controller in the storyboard, I get a 304 width. The weirdest behavior is that with FLEX, and after the render, the collection view measures 288 pixels.
The "only" difference is that the first view controller is just pushed, the second is contained in a UITabBarController.
PS : the first screen I'm talking about are the 3rd & 4th screenshots.
If someone has an explication to this, I'll take it ;)
Update 1 :
If I invalidate the collection view layout in - (void)viewDidLayoutSubviews, items are correctly drawn BUT there is like a flash because the whole collection view is redrawn (the header & items below).
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(self.collectionView.frame.size.width,
self.collectionView.frame.size.height);
}
and uncheck "Constrain to margins" and click on all dotted red constrain
so -8 padding will be gone in iPhone 6+
Storyboard
It makes a lot of sense when you approach the problem with a Storyboard. First, you will get a clear view of what you are designing. Second, you get to build your application with exactly 0 lines of code, leading to 0 bugs.
The parent UITabBarController and a set of UINavigationController is a common design pattern, and only when you implement it as follow do you get a proper UI behavior.
Code
You do not have to use a Storyboard to create the hierarchy above. You can embed each UIViewController in a UINavigationController programatically.
► Find this solution on GitHub and additional details on Swift Recipes.

UICollectionViewCell size and rotation

In my UICollectionView I have a cell that should take the entire width of the device. Here is how I set the size for the item:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(self.view.bounds.size.width, 120);
}
I have found that on rotation, the width of the cell does not change. I can resolve this using [collectionView.collectionViewLayout invalidateLayout] in didRotateFromInterfaceOrientation: but this isn't satisfactory. What if the user rotates while in another screen in my app? I will need to add the same to viewWillAppear. What about if the rotation occurs while the app is backgrounded? Now I need to add it for the UIApplicationDidBecomeActiveNotification notification.
What confuses me most is that this is not required for my custom headers in the same collection view. The following supplementary views correctly re-size on orientation change:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
return CGSizeMake(self.view.bounds.size.width, 40);
}
Where am I going wrong? What should I do to have the cells re-size automatically to fill the width of the collection view?
A bit late I know but could you solve this by subclassing flow layout and adding?
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return TRUE;
}

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?
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.
I used
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
UIButton *button = (UIButton *)[cell viewWithTag:2];
CGRect frame = cell.frame;
frame.size.width = button.frame.size.width;
cell.frame = frame;
}
}
and was able to resize my cell based on the width of the button subview in a little test app.
Make sure that the tags on your subviews are greater than 0 because if you use 0, it just gives you back the contentView. Other than that, this should get you there
Try collectionView:layout:sizeForItemAtIndexPath:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return self.view.frame.size;
}

UICollectionViewFlowLayout not invalidating right on orientation change

i have a UICollectionView with a UICollectionViewFlowLayout. I also implement the UICollectionViewDelegateFlowLayout protocol.
In my datasource i have a bunch of UIViewControllers which respond to a custom protocol so i can ask for their size and some other stuff.
In in the FlowLayout delegate when it asks for the sizeForItemAtIndexPath:, i return the item size which i get from my protocol. The ViewControllers which implement my protocol return a different item size depending on the orientation.
Now if i change the device orientation from portrait to landscape theres no problem (Items are larger in landscape) but if i change it back, i get this warning:
the item width must be less that the width of the UICollectionView minus the section insets left and right values.
Please check the values return by the delegate.
It still works but i don't like it to get warnings so maybe you can tell me what i am doing wrong. Also there is another problem. If i don't tell my collectionViews collectionViewLayout to invalidate in willAnimateRotationToInterfaceOrientation: the sizeForItemAtIndexPath: is never called.
Hope you understand what i mean. If you need additional information let me know :)
This answer is late, but the accepted answer didn't work for me. I sympathize with the OP in wanting a fire-and-forget UICollectionViewFlowLayout. I suggest that invalidating the layout in the view controller is in fact the best solution.
I wanted a single horizontal scrolling line of cells, centered in the view, in both portrait and landscape.
I subclassed UICollectionViewFlowLayout.
I overrode prepareLayout to recalculate the insets and then call [super prepareLayout].
I overrode the getter for collectionViewContentSize to make certain the content size was correct.
The layout didn't invalidate on its own even though the bounds were changing with the reorientation.
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// does the superclass do anything at this point?
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
// do whatever else you need before rotating toInterfaceOrientation
// tell the layout to recalculate
[self.collectionViewLayout invalidateLayout];
}
The UICollectionViewFlowLayout maintains the scroll position between orientations. The same cell will be centered only if it is square.
I used a combination of the two answers here to do what we are all trying to do really is make a collection view look like a table view but not use UITableView and get items in a single column (most likely)
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[self.collectionView.collectionViewLayout invalidateLayout];
}
I don't know if it can help to someone but none of the last answer help me because I'm using some UIViews into a UIScrollView.
I'm opening the UIViews programmatically depending on some events. So I can't use - (void) willRotateToInterfaceOrientation: and invalidateLayout or reloadData because:
1. invalidateLayout "occurs during the next view layout update cycle."
2. reloadData "For efficiency, the collection view only displays those cells and supplementary views that are visible."
What worked for me was use the width of the collectionView's parent (an UIView) in:
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
int currentWidth = self.frame.size.width;
UIEdgeInsets sectionInset = [(UICollectionViewFlowLayout *)collectionView.collectionViewLayout sectionInset];
int fixedWidth = currentWidth - (sectionInset.left + sectionInset.right);
For some reason the collectionView frame had the width of portrait at the time to call this function... using int currentWidth = self.frame.width help me to fix it.
A variation on #meelawsh's answer, but in Swift, and without a self.sizeForCollectionView property:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
guard let collectionView = self.collectionView else {
return
}
if size.width > collectionView.frame.width {
// bigger
let animation: (UIViewControllerTransitionCoordinatorContext)->(Void) = {
context in
collectionView.collectionViewLayout.invalidateLayout()
}
coordinator.animateAlongsideTransition(animation, completion: nil)
} else {
// smaller
collectionView.collectionViewLayout.invalidateLayout()
}
}
iOS8: the only way I could silence the warning is to call invalidate during the transition when rotating to a larger size and before transition when rotating to a smaller size.
self.sizeForCollectionView = size; //used to determine collectionview size in sizeForItem
if (size.width <= size.height) {
[self.collectionView.collectionViewLayout invalidateLayout];
}
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
if (size.width > size.height) {
[self.collectionView.collectionViewLayout invalidateLayout];
}
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
}];
The #0mahc0's answer worked for me, but only partially.
I don't have the rotate problem, because I force my app be only in Portrait mode, but my solution can help others with the same problem.
The warning shows every time the view appears. The reason of the warning is very clear, we have defined section insets to left and right of UICollectionView. Check interface builder and you will see in metrics those values defined.
The #0mahc0's solution works, but I want to stretch the cell to max width, so I removed the insets of section, otherwise I will have a 'margin' left and right.
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsZero;
}
Instead of implementing the delegate method you can go to interface builder and change value to zero of right and left insets.
One solution is to use KVO and listen for a change to the frame of the superview for your collection view. Calling -reloadData will work and get rid of the warnings. There is an underlying timing issue here...
// -loadView
[self.view addObserver:self forKeyPath:#"frame" options:NSKeyValueObservingOptionNew context:nil];
// -dealloc
[self.view removeObserver:self forKeyPath:#"frame"];
// KVO Method
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
[collectionView_ reloadData];
}

Resources