Search code examples
iosswiftuicollectionviewuicollectionviewcellcollectionview

Editing the width of a CollectionViewCell


I am trying to edit the width of the cell so that no matter what screen size, I will have score1.count cells in a row. The code I am using for my Collection View is the following:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    cell.myLabel.text = String(self.items[indexPath.item])

    return cell
}

This is the function targeting the width of the cell.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
    let size = Int(self.view.frame.size.width)/(score1.count + 1)
    return CGSize(width: CGFloat(size), height: 80)
}

I have spent many hours looking at different sources and trying different things, but the collection view never has the right number of cells. One idea is that it may be because I have the cell size set in auto layout but whenever I go to change it xcode crashes. Any ideas on bypassing the auto layout? Or how to change the auto layout?

Thanks!


Solution

  • try this

    extension YourViewController : UICollectionViewDelegateFlowLayout{
    
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let rowItems:CGFloat = 4
        let padding:CGFloat = 2
        let width = (collectionView.bounds.width / rowItems) - padding //Change width as per your requirement
        let height = collectionView.bounds.height - (2 * padding)//Change height as per your requirement
        return CGSize(width: width, height: height)
      }
    
    }