How to set UICollectionViewCell Width and Height programmatically

SwiftUicollectionview

Swift Problem Overview


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 ?

Swift Solutions


Solution 1 - Swift

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)));
}

Solution 2 - Swift

If one is using storyboard and overriding UICollectionViewDelegateFlowLayout then in swift 5 and Xcode 11 also set Estimate size to None enter image description here

Solution 3 - Swift

Make sure to add the protocol UICollectionViewDelegateFlowLayout in your class declaration

class MyCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout
{
    //MARK: - UICollectionViewDelegateFlowLayout
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
       return CGSize(width: 100.0, height: 100.0)
    }
}

Solution 4 - Swift

Finally got the answer. You should extend UICollectionViewDelegateFlowLayout
This should be working with answers above.

Solution 5 - Swift

Swift 4

You have 2 ways in order to change the size of CollectionView.
First way -> add this protocol

UICollectionViewDelegateFlowLayout

for In my case I want to divided cell into 3 part in one line. I did this code below

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
            // In this function is the code you must implement to your code project if you want to change size of Collection view
            let width  = (view.frame.width-20)/3
            return CGSize(width: width, height: width)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = collectionData[indexPath.row]
        }
        return cell
    }
}

Second way -> you don't have to add UICollectionViewDelegateFlowLayout but you have to write some code in viewDidload function instead as code below

class ViewController: UIViewController {
@IBOutlet weak var collectionView1: UICollectionView!
        var collectionData = ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10.", "11.", "12."]

    override func viewDidLoad() {
        super.viewDidLoad()
        let width = (view.frame.width-20)/3
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: width, height: width) 
    }
}


extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
   

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = collectionData[indexPath.row]
        }
   
        return cell
    }
}

Whatever you write a code as the first way or second way you will get the same result as above. I wrote it. It worked for me

enter image description here

Solution 6 - Swift

Size ratio according to iPhone size :

Here's what you can do to have different width and height for cell's regarding the iPhone size :

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 12 * 3) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}

And maybe you should also disable your AutoLayout constraints on cell for this answer to work.

Solution 7 - Swift

in Swift3 and Swift4 you can change cell size by adding UICollectionViewDelegateFlowLayout and implementing it's like this :

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

or if create UICollectionView programmatically you can do it like this :

    let layout = UICollectionViewFlowLayout()
                    layout.scrollDirection = .horizontal //this is for direction
                    layout.minimumInteritemSpacing = 0 // this is for spacing between cells
                    layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height) //this is for cell size
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)

Solution 8 - Swift

The collection view has a layout object. In your case, it is probably a flow layout (UICollectionViewFlowLayout). Set the flow layout's itemSize property.

Solution 9 - Swift

swift4 swift 4 ios collection view collectionview example xcode latest code working sample

Add this on Delegate section of the top

UICollectionViewDelegateFlowLayout

and use this function

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 20) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}

///// sample complete code

create on collection view and collectionview cell in storyboard give reference to the collection as
@IBOutlet weak var cvContent: UICollectionView!

paste this in View controller

 import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var arrVeg = [String]()
    var arrFruits = [String]()
    var arrCurrent = [String]()
    
    @IBOutlet weak var cvContent: UICollectionView!
    
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
        arrVeg = ["Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato"]
        
        arrVeg = ["Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange"]
        
        
        arrCurrent = arrVeg
    }
    //MARK: - CollectionView
    


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (self.view.frame.size.width - 20) / 3 //some width
        let height = width * 1.5 //ratio
        return CGSize(width: width, height: height)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        return arrCurrent.count
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCollectionViewCell
        cell.backgroundColor =  UIColor.green
        return cell
    }
}

Solution 10 - Swift

Try below method

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: 100.0, height: 100.0)
}

Solution 11 - Swift

Swift 5 Programmatically

lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        
        //Provide Width and Height According to your need
        let cellWidth = UIScreen.main.bounds.width / 10
        let cellHeight = UIScreen.main.bounds.height / 10
        layout.itemSize = CGSize(width: cellWidth, height: cellHeight)
        
        //You can also provide estimated Height and Width
        layout.estimatedItemSize = CGSize(width: cellWidth, height: cellHeight)
    
        //For Setting the Spacing between cells
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        return UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    }()

Solution 12 - Swift

Swift 5

Add these protocols

 - `UICollectionViewDelegate`
   
   
 - `UICollectionViewDataSource`
   
 
 - `UICollectionViewDelegateFlowLayout`

Your code will then look like this

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)
    }
}

Now the final and crucial step to see this take effect is to go to your viedDidLoad function inside your Viewcontroller.

    override func viewDidLoad() {
        super.viewDidLoad()
        collection.dataSource = self // Add this
        collection.delegate = self // Add this
        
        // Do any additional setup after loading the view.
    }

Without telling your view which class the delegate is it won't work.

Solution 13 - Swift

An other way is to set the value directly in the flow layout

    let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = CGSize(width: size, height: size)

Solution 14 - Swift

A simple way:

If you just need a simple fixed size:

class SizedCollectionView: UIICollectionView {
    override func common() {
        super.common()
        let l = UICollectionViewFlowLayout()
        l.itemSize = CGSize(width: 42, height: 42)
        collectionViewLayout = l
    }
}

That's all there is to it.

In storyboard, just change the class from UICollectionView to SizedCollectionView.

But !!!

Notice the base class there is "UI 'I' CollectionView". 'I' for Initializer.

It's not that easy to add an initializer to a collection view. Here's a common approach:

Collection view ... with initializer:

import UIKit

class UIICollectionView: UICollectionView {
    private var commoned: Bool = false
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        if window != nil && !commoned {
            commoned = true
            common()
        }
    }
    
    internal func common() {
    }
}

In most projects, you need "a collection view with an initializer". So you will probably anyway have UIICollectionView (note the extra I for Initializer!) in your project.

Solution 15 - Swift

So you need to setting from storyboard for attribute for collectionView in cell section estimate Size to none, and in your ViewController you need had delegate method for implementing this method : optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize

Solution 16 - Swift

Try to use UICollectionViewDelegateFlowLayout method. In Xcode 11 or later, you need to set Estimate Size to none from storyboard.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: 
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let padding: CGFloat =  170
    let collectionViewSize = advertCollectionView.frame.size.width - padding
    return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
}

Solution 17 - Swift

Absolutely simple way:

class YourCollection: UIViewController,
     UICollectionViewDelegate,
     UICollectionViewDataSource {

You must add "UICollectionViewDelegateFlowLayout" or, there is no autocomplete:

class YourCollection: UIViewController,
     UICollectionViewDelegate,
     UICollectionViewDataSource,
     UICollectionViewDelegateFlowLayout {

Type "sizeForItemAt...". You're done!

class YourCollection: UIViewController,
     UICollectionViewDelegate,
     UICollectionViewDataSource,
     UICollectionViewDelegateFlowLayout {
 
     func collectionView(_ collectionView: UICollectionView,
      layout collectionViewLayout: UICollectionViewLayout,
      sizeForItemAt indexPath: IndexPath) -> CGSize {
     
     return CGSize(width: 37, height: 63)
}

That's it.

Example, if you want "each cell fills the whole collection view":

     guard let b = view.superview?.bounds else { .. }
     return CGSize(width: b.width, height: b.height)

Solution 18 - Swift

Swift 5, Programmatic UICollectionView setting Cell width and height

// MARK: MyViewController

final class MyViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        let spacing: CGFloat = 1
        let numOfColumns: CGFloat = 3
        let itemSize: CGFloat = (UIScreen.main.bounds.width - (numOfColumns - spacing) - 2) / 3
        layout.itemSize = CGSize(width: itemSize, height: itemSize)
        layout.minimumInteritemSpacing = spacing
        layout.minimumLineSpacing = spacing
        layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
        return layout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout)
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureCollectionView()
    }
    
    private func configureCollectionView() {
        view.addSubview(collectionView)
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
        ])
        collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: "PhotoCell")
    }
    
    // MARK: UICollectionViewDataSource

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
        cell.backgroundColor = .red
        return cell
    }
    
}

// MARK: PhotoCell

final class PhotoCell: UICollectionViewCell {
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init?(coder:) not implemented")
    }
    
    func setupViews() {
        addSubview(imageView)
        NSLayoutConstraint.activate([
            topAnchor.constraint(equalTo: topAnchor),
            bottomAnchor.constraint(equalTo: bottomAnchor),
            leadingAnchor.constraint(equalTo: leadingAnchor),
            trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
    }
    
}

Solution 19 - Swift

If, like me, you need to keep your custom flow layout's itemSize dynamically updated based on your collection view's width, you should override your UICollectionViewFlowLayout's prepare() method. Here's a WWDC video demoing this technique.

class MyLayout: UICollectionViewFlowLayout {
	
	override func prepare() {
		super.prepare()
		
		guard let collectionView = collectionView else { return }
		
		itemSize = CGSize(width: ..., height: ...)
	}
	
}

Solution 20 - Swift

If you are not using UICollectionViewController, you need to add conformance to it by setting delegates UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout.

  extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout

After that, you have to set a delegate to your collection view that is added to ViewController.

  collectionView.delegate = self
  collectionView.dataSource = self


  

And finally, you have to add layout to your collection view:

  let collectionLayout = UICollectionViewFlowLayout()
  collectionView.collectionViewLayout = collectionLayout

After these steps, you can change size in func:

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize

Solution 21 - Swift

The answer for storyBoard users is: "In size inspector change your collection cell size from custom to Automatic".

screenshot link

Solution 22 - Swift

This is my version, find your suitable ratio to get the cell size as per your requirement.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJVSView Question on Stackoverflow
Solution 1 - SwiftPinkeshGjrView Answer on Stackoverflow
Solution 2 - SwiftSpydyView Answer on Stackoverflow
Solution 3 - Swiftpierre23View Answer on Stackoverflow
Solution 4 - SwiftsaburoView Answer on Stackoverflow
Solution 5 - SwiftSup.IaView Answer on Stackoverflow
Solution 6 - SwiftAnthoPakView Answer on Stackoverflow
Solution 7 - SwiftMohsen mokhtariView Answer on Stackoverflow
Solution 8 - SwiftmattView Answer on Stackoverflow
Solution 9 - SwiftUllas PujaryView Answer on Stackoverflow
Solution 10 - SwiftNilesh PatelView Answer on Stackoverflow
Solution 11 - SwiftShubham MishraView Answer on Stackoverflow
Solution 12 - SwiftTakaView Answer on Stackoverflow
Solution 13 - SwiftAntziView Answer on Stackoverflow
Solution 14 - SwiftFattieView Answer on Stackoverflow
Solution 15 - SwiftdgalluccioView Answer on Stackoverflow
Solution 16 - SwiftMuhammad Shariq HasnainView Answer on Stackoverflow
Solution 17 - SwiftFattieView Answer on Stackoverflow
Solution 18 - SwiftSuhit PatilView Answer on Stackoverflow
Solution 19 - SwiftmattsvenView Answer on Stackoverflow
Solution 20 - SwiftVladimir SukanicaView Answer on Stackoverflow
Solution 21 - SwiftHasnat AsgharView Answer on Stackoverflow
Solution 22 - SwiftRahul K RajanView Answer on Stackoverflow