6

For UICollectionViews, is it possible to have multiple cell types?

For example:

media_cell

regular_cell

ad_cell

Would you just have to register them or do you have to include an if statement and change the layout according to some variable to achieve this effect.

For example:

if cell.ad == true {

}

The reason being, I want a slightly different sized cell for when an image is present. I guess resizing the cell could work but I haven't seen anything on this online.

Any suggestions

Ravi Dhorajiya
  • 1,441
  • 3
  • 19
  • 26
Stefan
  • 822
  • 1
  • 10
  • 26

2 Answers2

9

Try this: 1. Register two(or more) cells. 2.Configure cellforItem for each. 3. Configure sizeForItem for each. First:

self.collectionView.register(SmallCell.self, forCellWithReuseIdentifier: "smallCell")
self.collectionView.register(BigCell.self, forCellWithReuseIdentifier: "bigCell")

And then:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     if dataSource[indexPath.item].hasImage {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “smallCell”, for: indexPath) as! SmallCell
        let model = dataSource[indexPath.item]
        cell.model = model
        return cell
      } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “bigCell”, for: indexPath) as! BigCell
        let model = dataSource[indexPath.item]
        cell.model = model
        return cell
       }   
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
     if dataSource[indexPath.item].hasImage {
        return CGSize(width: collectionView.frame.width, height: cellHeight+100)
     } else {   
        return CGSize(width: collectionView.frame.width, height: cellHeight)    
     }       
}
Nebojsa Nadj
  • 572
  • 2
  • 12
  • how do I reference the data source? – Stefan May 15 '17 at 05:09
  • What do you mean? dataSource is just an example array I made up. Where each element in array has a Bool hasImage. This is just dummy code. That if statement can be written a hundred different ways. You yourself should know which indexPaths should have a image, which shouldn't. – Nebojsa Nadj May 15 '17 at 05:14
3

Two things and everything should be works:

  1. You can register any number of cells in one collection view.
  2. Check out self-sizing cells topic and you should not worry about different sizes of cells.

Great tutorial

More info in this brilliant answer here

Good luck :)

Community
  • 1
  • 1
Kamil Harasimowicz
  • 3,534
  • 5
  • 26
  • 48