动态调整单元格大小时出错

时间:2016-11-28 06:22:42

标签: ios swift

我尝试使用以下代码单独调整单元格大小。

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!

}

但我总是得到致命的错误:在此行展开一个可选值时意外地发现了nil

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

如果我删除了阻止,那么其他一切都很完美......任何人都知道发生了什么事?

提前致谢。

已编辑:已添加CellForItemAt功能

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
}

1 个答案:

答案 0 :(得分:1)

sizeForItemAt()之前调用

cellForItemAt(),因此您尝试从单元格中获取信息(其图像大小),但尚未创建单元格。

我在cellForItemAt()上看到您使用数组生成图片,请考虑在sizeForItemAt()中使用相同的数组来获取图片大小,例如size func的开头可能看起来像;

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
    ...
}