iOS UICollectionView prototype cell size property ignored
The size of the cell in the storyboard editor is just to help you design the cell. Since each prototype cell can be a different size, UICollectionView doesn't know which cell's size to pick for all the cells. That's why you set the actual size you want to use for your cells separately. You can do it in the designer by selecting the collection view and setting its Cell Size Width and Height in the Size inspector, under the "Collection View Size" heading.
Or, you can override the following method and return a CGSize object that specifies the size you want to use for each cell. Using this method, you can actually have each cell be a different size:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
Example:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(100, 100);
}
Your view controller needs to be a delegate of UICollectionViewDelegateFlowLayout in order for this method to be called. So don't forget to add that delegate declaration to your view controller's .h file, such as:
@interface MyViewController () <UICollectionViewDelegateFlowLayout>
Swift
extension MyViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
If all the cells are the same size and you can set the itemSize
on the UICollectionViewFlowLayout
Example:
((UICollectionViewFlowLayout *) self.collectionViewLayout).itemSize = CGSizeMake(100, 100);
Swift, working for latest iOS.
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = cellSize
I don't have enough points to reply to Sam, but the key is that it's not UICollectionViewLayout but UICollectionViewFlowLayout.