How to set UICollectionViewCell Width and Height programmatically

JVS picture JVS · Jun 25, 2016 · Viewed 207.3k times · Source

I am trying to implement a CollectionView. When I am using Autolayout, my cells won't change the size, but their alignment.

Now I would rather want to change their sizes to e.g.

//var size = CGSize(width: self.view.frame.width/10, height: self.view.frame.width/10)

I tried setting in my CellForItemAtIndexPath

collectionCell.size = size

it didn't work though.

Is there a way to achieve this?

edit:

It seems, that the answers will only change my CollectionView width and height itself. Is there are conflict in Constraints possible? Any ideas on that ?

Answer

PinkeshGjr picture PinkeshGjr · Jun 25, 2016

Use this method to set custom cell height width.

Make sure to add this protocols

UICollectionViewDelegate

UICollectionViewDataSource

UICollectionViewDelegateFlowLayout

If you are using swift 5 or xcode 11 and later you need to set Estimate Size to none using storyboard in order to make it work properly. If you will not set that than below code will not work as expected.

enter image description here

Swift 4 or Later

extension YourViewController: UICollectionViewDelegate {
    //Write Delegate Code Here
}

extension YourViewController: UICollectionViewDataSource {
    //Write DataSource Code Here
}

extension YourViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: screenWidth, height: screenWidth)
    }
}

Objective-C

@interface YourViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(CGRectGetWidth(collectionView.frame), (CGRectGetHeight(collectionView.frame)));
}