Multiple cells for a single UICollectionView

2019-05-18 00:50发布

问题:

In my collection view, the cell class must have completely different appearance for different kinds of data in the array.

I am looking for a way to create multiple cells and choose a different one according to the input data, so for example :

internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell1 = collectionView.dequeueReusableCell..  as! kind1
    let cell2 = collectionView.dequeueReusableCell.. as! kind2
   // here choose a different one for each kind of data
    return cell1
}

I am trying to understand if :

  1. How to do this and if its the right way in terms of memory ?
  2. Is it a good design? how would you go about making a completely different layout of a single cell? ( creating views and hiding them seems like a bad approach)

回答1:

You need to do something like this

internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if (data.kind == kind1) {
        let cell1 = collectionView.dequeueReusableCell..  as! kind1

        return cell1
    } else {
        let cell2 = collectionView.dequeueReusableCell.. as! kind2

        return cell2
    }
}

by checking the type of the data you can determine the cell.



回答2:

I just want to mention this, for any future users who might wonder how to do that. Now, I think it's much easier to just use the indexPath.item and check whether or not it's cell 1 or cell 2. Here's an example

if indexPath.item == 0 
{
   // Cell 1
   let cell1 = let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell1", for: indexPath) as! Cell1
   return cell1
}
else
{
   // Cell 2
   let cell2 = let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell2", for: indexPath) as! Cell1
   return cell2
}

In case you have more than 2 custom UICollectionViewCells then just add else if statements and check against its indexPath.item.