在UICollectionViewCell中更改项目大小

时间:2016-12-10 23:58:09

标签: swift uicollectionview uicollectionviewcell uicollectionviewlayout

我正在尝试更改UICollectionViewCell内的特定项目大小

在我的 UIViewController 中,我声明如下:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Storyboard.CellIdentifier, for: indexPath) as! NameCollectionViewCell

    if(retreivedEvents == nil) {
     // print("data not received yet...")
        return cell
    } else {
     // print("new data given")
        cell.anEvent = self.retreivedEvents![indexPath.row]
        cell.setNeedsLayout()
        return cell
    }
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {

    let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: Storyboard.CellIdentifier, for: indexPath) as! NameCollectionViewCell

    let screenHeigh =  UIScreen.main.bounds.size.height

    cell2.frame.size.height = cellSize * 0.8
    cell2.descriptionTextView.frame.size.height += 50
    cell2.theImageView.frame.size.height = cellSize * 0.8

    let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)  
    return CGSize(width: self.collectionView.frame.width,height:cell2.frame.size.height)
}

问题: 每次运行时,控制台都会显示

  

使用NSException类型的未捕获异常终止

。我不确定错误是什么。

enter image description here

1 个答案:

答案 0 :(得分:0)

现在,我不是100%,但我会非常小心为sizeForItem内的特定索引路径出列单元格。您正在使用单元格实例来计算大小,但您不想使用集合视图已在使用的单元格实例。您可以通过使用不forIndexPath的出列方法来避免这种情况。