【发布时间】:2015-12-12 03:01:45
【问题描述】:
我在UIViewController 中添加了一个UICollectionView,并为其创建了一个自定义单元格。
我使用sizeForItemAtIndexPath 方法设置单元格的大小,并将每个单元格的高度和宽度都设置为UIScreen.mainScreen().bounds.width/2。所以本质上,每个单元格的宽度是屏幕的一半,高度也是相同的长度。
然后我在单元格内有一个UIImageView,每个边缘都固定到单元格的相对边缘,以便图像视图填充单元格。我还有一个UILabel,它在单元格中垂直和水平居中。
但是在第一次加载时,单元格的大小是正确的,但左上角的一个小方块中的内容要小得多。 (如下图所示,我已将单元格的 contentView 背景颜色设置为绿色,imageView 背景颜色设置为红色)。
然后在向下滚动一点之后(我假设一个可重复使用的单元格正在出队)所有单元格都很好(并且在向上滚动后仍然很好)。
是什么导致内容在首次加载时没有被正确限制?
更新
部分代码来自我的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
}
【问题讨论】:
-
显示
UIViewController -
你的意思是显示
UIViewController的代码? -
我为
UICollectionView添加了一些代码。不确定您到底想看什么? -
几乎看起来像默认的 100x100px 单元格大小。如果你在 Xcode 中使用视图调试器,是单元格本身还是 contentView 仍然使用默认大小?如果在单元格上设置完所有内容后调用 layoutIfNeeded 会发生什么?
-
@DepartamentoB 在视图层次调试器中,当我选择实际单元格本身时,它是绿色背景的大小,而不是红色小方块。此外,刚刚尝试在
return cell在cellForRowAtIndexPath方法中调用cell.layoutIfNeeded()之前,这解决了它!在这里做这件事是件好事吗?它到底在做什么,有什么缺点吗?应该在我放的cellForRowAtIndexPath中调用它还是在其他地方调用它?
标签: ios objective-c swift uicollectionview uicollectionviewcell