Is it possible to get a cell's tag within the collectionview sizeForItemAtIndexPath delegate method?

923 Views Asked by At

When I call the following delegate method:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    float cellWidth = 90.0f; float cellHeight = 60.0f;

    int cellType = [[collectionView cellForItemAtIndexPath:indexPath] tag];

    return CGSizeMake(cellWidth, cellHeight);

}

cellType returns 0. [collectionView cellForItemAtIndexPath:] also returns nil

I am guessing this is because the cell is not sized, so it is not displayed, and when it's not displayed, it returns nil (i.e. this method is called prior to the instance of the cell object being created).

Is there a way to get information that was set for this item in the collectionView:cellForItemAtIndexPath method? How can an individual cell type be identified within the sizeForItemAtIndexPath method?

(I plan on using the data source NSArray, but I was trying to keep this logic within the display object, and not managed by the data.)

3

There are 3 best solutions below

1
On

Thinking here of doing something like:

var cell;

if let (cell = collectionView.cellForItemAtIndexPath(indexPath))
{
   //get the cell's tag and do what is needed.
}

But I don't know if cell will return a value or not in the sizeForCell Method

0
On

If you need to get the cell first you need to dequeue it. because layoutAttributesForItemAtIndexPath will be get called before itemAtIndexPath that was the reason you are getting nil.

Secondly You will get the tag for item only if you are reusing that view other wise all view have same tag 0. But If you know about which identifier is used for dequeuing the cell use that identifier to give your conditional height.

0
On

I don't think tag is reliable because of cell reuse. I would suggest using the same logic you are using in cellForItemAtIndexPath to identify the data in your NSArray. Then determine what size to return based on the data. In other words, rely on your data source in both cellForItemAtIndexPath and sizeForItemAtIndexPath, instead of making sizeForItemAtIndexPath dependent on cellForItemAtIndexPath.