user3608914 user3608914 - 7 days ago 4
iOS Question

Error with dynamically resizing cell size

I try to resize the cell individually by employing the following code.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var itemSize : CGSize?

let currentCell = self.collectionView?.cellForItem(at: indexPath) as! CustomCell
let imageSize : CGSize = (currentCell.imageView?.image?.size)!
let aspectRatio : CGFloat = imageSize.width / imageSize.height

if aspectRatio > 1 {
itemSize = CGSize(width: self.maxItemSize.width, height: maxItemSize.height / aspectRatio)
}else{
itemSize = CGSize(width: self.maxItemSize.width * aspectRatio, height: maxItemSize.height)
}

return itemSize!

}


But i always obtain fatal error: unexpectedly found nil while unwrapping an Optional value at this line

let currentCell = self.collectionView?.cellForItem(at: indexPath) as! CustomCell


if i remove the block, then everything else works perfectly.. Anyone knows what is going on?

Thanks in advance.

Edited: Added CellForItemAt Function

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CustomCell
cell.backgroundColor = colorArray[indexPath.section]
cell.imageView?.image = imageArray[indexPath.item]
return cell
}

Answer

sizeForItemAt() gets called before cellForItemAt(), so you are trying to grab information from the cell (its image size) but the cell hasn't been created yet.

I see that on your cellForItemAt() you use an array for the images, consider using the same array in sizeForItemAt() to grab the image size, for example the beginning of your size func could look like;

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    var itemSize : CGSize?

    // delete this line** let currentCell = self.collectionView?.cellForItem(at: indexPath) as! CustomCell
    // let imageSize : CGSize = (currentCell.imageView?.image?.size)!
    let imageSize : CGSize = imageArray[indexPath.item].size // or indexPath.row depending on your structure
    let aspectRatio : CGFloat = imageSize.width / imageSize.height
    ...
}
Comments