首次加载时UICollectionViewCell内容大小错误

myl*_*les 31 objective-c ios uicollectionview uicollectionviewcell swift

我有一个添加UICollectionView到我的,UIViewController并为它制作了一个自定义单元格.

我使用该sizeForItemAtIndexPath方法设置单元格的大小,并将每个单元格设置为UIScreen.mainScreen().bounds.width/2高度和宽度.基本上,每个单元格都是屏幕宽度的一半,高度相同.

然后我UIImageView在单元格内部,每个边缘固定到单元格的相对边缘,以便图像视图填充单元格.我也有一个UILabel在细胞中垂直和水平居中的.

但是,在第一次加载时,单元格的大小正确,但内容在左上角的小方块中要小得多.(如下图所示,我将单元格的contentView背景颜色设置为绿色,将imageView背景颜色设置为红色).

在此输入图像描述

然后向下滚动一点(我假设一个可重复使用的单元格出列)所有单元格都很好(滚动后再保持正常).

在此输入图像描述

是什么导致内容在首次加载时不能正确约束?

UPDATE

我的一些代码UIViewController:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell = collectionView.dequeueReusableCellWithReuseIdentifier("PrevDrawCell", forIndexPath: indexPath) as? PrevDrawCell

        if cell == nil {
            cell = PrevDrawCell()
        }

        cell!.drawVC = self
        cell!.imageShortCode = self.tempImageURLs[indexPath.row]

        // Pull image (async) and set after download
        cell!.setupImage()

        cell!.contentView.backgroundColor = UIColor.greenColor()
        cell!.coverView.backgroundColor = UIColor.redColor()

        cell!.dateLabel.font = UIFont(name: "HelveticaNeue-Light", size: 26)
        cell!.dateLabel.text = "\(self.tempImageURLs.count-indexPath.row)/9"

        return cell!
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let size = UIScreen.mainScreen().bounds.width/2
        return CGSize(width: size, height: size)
}


func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsZero
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}
Run Code Online (Sandbox Code Playgroud)

Dep*_*o B 60

它看起来仍然保留了contentView的100x100px基本大小,而单元格本身已经获得了正确的大小.您可以强制布局重置在返回单元格之前添加以下行:

cell?.layoutIfNeeded()
Run Code Online (Sandbox Code Playgroud)

  • 使用**layoutIfNeeded()**来解决第一次加载单元格或视图时可能遇到的任何大小相关问题,除非你调用**layoutIfNeeded()**它将等待下一个绘制周期应用大小相关的更改,但调用**layoutIfNeeded()**立即应用这些更改!代码少,效果更大!! (3认同)
  • 由于某种原因,这是我从来没有工作过的事情。我正在使用具有动态像元高度的完全自动布局,可能与此解决方案不兼容?即使执行layoutIfNeeded,当我检查单元格的帧大小时,它始终以IB中设置的大小进行响应。通常只有在向后滚动后,才会响应正确的自动布局大小。 (2认同)

tri*_*ode 36

对我有用的Estimate Size是将集合视图从自动更改为无。

集合视图估计大小


小智 5

我曾经有过类似的问题(即使使用正确的自动布局,单元格的内容也不适合单元格)。该错误是由于未调用 super.layoutSubviews()Cell类中的重写函数layoutSubviews()引起的。