Search code examples
iosswiftuicollectionviewcell

Mix-Matching Collection View Cells within a 1-Section Collection View


I have two different cells: A & B. (where the only difference between A & B is that they have 2 different properties.

I'm trying to get A and B to show up vertically in a collection view like this:

A B A B A B A B

How do I go about doing this in the cellForItemAt method? Maybe by keeping track of which cell was returned last?


Solution

  • There are a few approaches you can take to achieve something like this. If all of your data is the same but you want every other cell to appear differently you can just check to see if it is an even or an odd row when in your datasource methods.

    Something like this:

    if indexPath.row % 2 != 1 // odd row
    {
       // set up a cell of type A
    }
    else // even row
    {
      // set up a cell of type B
    }
    

    Otherwise, if your actual data source can discern the different elements in the array as being of different types, you would just check to see what type of element is in your array at a given index and return the appropriate cell.