I am working programmatically (no storyboard) and am having trouble making layout.itemSize dynamic for different screen sizes. I get this error message:
"UICollectionView must be initialised with a non-nil layout parameter"
with the following code in my implementation file:
- (instancetype)init
{
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
CGSize size = self.collectionView.bounds.size;
layout.itemSize = CGSizeMake(size.width, size.height);
[layout setScrollDirection:UICollectionViewScrollDirectionVertical];
layout.minimumLineSpacing = 100.0;
layout.headerReferenceSize = CGSizeMake(0.0, 50.0);
return (self = [super initWithCollectionViewLayout:layout]);
}
I don't get the error message if I use "100,100" for example for layout.itemSize
. Is there a way to make it dynamic though?
I am new to Objective-C so would appreciate any help on what I am doing incorrectly.
An abstract base class for generating layout information for a collection view.
A layout object that organizes items into a grid with optional header and footer views for each section.
Need to use the flow delegate method:
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize cellSize = CGSizeMake(width, height);
return cellSize;
}
You specify the width and height float values to whatever you want.
For example, lets say your CollectionView is vertical and you want a short header view, a big middle view and a small footer view, then you could do something like:
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize cellSize;
cellSize.width = self.view.bounds.size.width;
if(indexPath.row == 0)
{
// header view height
cellSize.height = 100;
}
else if(indexPath.row == 1)
{
// body view height
cellSize.height = 500;
}
else
{
// assuming number of items is 3, then footer view is last view
// footer view height
cellSize.height = 100;
}
return cellSize;
}
add following delegate method to your collection view
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
UIImage *image;
long row = [indexPath row];
image = [UIImage imageNamed:_carImages[row]];
return image.size;
}
here a link which help you enter link description here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With