0

I have a simple collection view on a ViewController. It is a single, horizontally-scrolling strip. There are unlimited number of cells that will either be of type A or B. Each class of cell has a different width (A=160, B=40).

So the collection array might be AABBABAABA and the collection view cell widths should alter according to the type of cell.

I've tried to set the cell widths in the attributes. I've tried determining the width to use via tags, isKindOfClass, tintColors, viewDidLoad etc. Nothing seems to work so I assume it's more complicated than first thought.

I have implemented the following but it always chooses 160 width since tag is always found to be nil. I think I am missing a layout or something?

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if collectionView.cellForItemAtIndexPath(indexPath)?.tag == 111 {
        return CGSize(width: 40, height: 80)
    } else {
        return CGSize(width: 160, height: 80)
    }
}

The tag is recognised within the didSelectItemAtIndexPath function but seemingly not within the sizing function.

Anyone any ideas?

Thanks

RobertyBob
  • 803
  • 1
  • 8
  • 20

2 Answers2

0

I think a way to do this would be to have an array property storing the index paths of the wide cells. In the delegate function you'd just do this:

    return wideCellsIndexPaths.contains(indexPath) ? 
CGSize(width: 160, height: 80) : CGSize(width: 40, height: 80)
binchik
  • 909
  • 8
  • 10
  • thx binchik - seems that there is no actual answer contained within the collection view functions or setup so will accept your answer as correct although, of course, it is only one of many possible solutions if having to store the cell data in an external array or setting. – RobertyBob May 25 '16 at 09:16
0

if you have only 2 cell just make condition on the base of indexpath.row avoid the tags. hope it willl work for you.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    if indexPath.row == 0 {
        return CGSizeMake(40,80)
    } else {
        return CGSizeMake(160,80)
    }
}
  • Sorry - wasn't clear - will edit question. The collection view has unlimited cells but they are always either type A or B, but might be AAABAABBBAB etc. – RobertyBob May 23 '16 at 11:32