Registering multiple cells in UICollectionView (sw

2019-02-22 11:07发布

问题:

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

回答1:

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


回答2:

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