UICollectionViewCell内容在第一次加载时大小错误

我有一个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 } 

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

 cell?.layoutIfNeeded() 

我曾经有过类似的问题(即使使用正确的自动布局,我的细胞内容也不适合细胞)。 该错误是由于在Cell的类中的overriden函数layoutSubviews()中没有调用super.layoutSubviews()而引起的。