IOS UICollectionview Dynamically change Cell's Height
As far as I understand, you want to replicate the layout of this test.
You need to understand better how UICollectionView
works like here
You will have to change the number of items in your UICollectionView
in this delegate method:
- (NSInteger)numberOfItemsInSection:(NSInteger)section;
Here, you want to return 4 at the beginning of the test, then 4*2, 4*2*2, and so on. This will gives you the correct number of item.
Then the layout. you should have multiple values for it, as you don't want the same space between your elements as the beginning and at the end. I would go for reducing the space as the number of items grows.
You need to be careful with the spacing, because it can cause a cell to be forced in the next line
You already did a great job by dividing the frame to get the maximum height & width of a cell, but your
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
Method is really messy.
As you will not have an unlimited number of items in your UICollectionView
, you can use a switch statement
, and in each switch you return the computed CGSize
of the cell.
For example, you can use it like this:
switch (numberOfHorizontalItems) { case 2: return CGSizeMake(self.collectionView.frame.size.width/2.5,self.collectionView.frame.size.width/2.5); break; case 4: return CGSizeMake(self.collectionView.frame.size.width/4.5,self.collectionView.frame.size.width/4.5); break; case 8: CGSizeMake(self.collectionView.frame.size.width/8.5,self.collectionView.frame.size.width/8.5); break;(And so on) default: break; }
You should note that the computed CGSize
displayed here have to incorporate the spacing / merging between the items
You also don't need viewWillLayoutSubviews
and viewDidLayoutSubviews
, you just need to call [self.collectionView reloadData]
when the user tapped a cell (or in the method handling the logic after an user tapped a cell)
Finally, if you don't want the UICollectionView
to be scrollable, just set the property self.collectionView.scrollEnabled = NO;
Follow this blog link which illustrate in very easy manner with example code:- http://www.fantageek.com/1468/ios-dynamic-table-view-cells-with-varying-row-height-and-autolayout/
The upper link is for table view but in the same manner you can work on collection view and achieve your desired result.
Note: It is all about content hugging vs content compression resistance priority.
Use this GitHub CHTCollectionViewWaterfallLayout is a subclass of UICollectionViewLayout, and it trys to imitate UICollectionViewFlowLayout's usage as much as possible.
This layout is inspired by Pinterest. It also is compatible with PSTCollectionView.