我制作了一个包含 144 个单元格的 Collection View 。我将它们设置为单选。我一直在玩我的设置有一段时间了,但是任何实际正确显示单元格的设置都有这个问题,即两个特定单元格的大小始终错误。请注意,该问题仅在 iPad pro 上测试时出现。它们会经常在我无法复制的条件下调整大小,来回将它们的图像更改为其他图像。我尝试仅在绝对必要时调用 reloadData(),并在 indexPath 函数中调用重新加载单个单元格。我已经测试了我能想到的一切,以防止这成为一个问题。任何指向正确方向的指示都将不胜感激!
这是我的代码:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ChartViewCell
cell.setColor(colorArray[indexPath.section][indexPath.row])
cell.overlay?.image = cell.whichColor.toImage()
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 24
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 12
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionView, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 0, 0, 0)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let screenRect: CGRect = collectionView.bounds
let screenWidth: CGFloat = screenRect.size.width
let cellWidth: CGFloat = screenWidth / 24
//Replace the divisor with the column count requirement. Make sure to have it in float.
let size: CGSize = CGSizeMake(cellWidth, cellWidth)
return size
}
最佳答案
我在之前的项目中确实遇到了同样的问题。我设法通过使用这个库解决了这个问题:Snapkit .在pod中导入库,在cellForItemAtIndexPath
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! ChartViewCell
let width = self.view.bounds.size.width / 24
cell.overlay.snp_makeConstraints { (make) -> Void in
make.width.equalTo(width)
make.height.equalTo(width)
}
cell.setColor(colorArray[indexPath.section][indexPath.row])
cell.overlay?.image = cell.whichColor.toImage()
return cell
}
只需在 Storyboard 中的 imageView 上放置顶部和前导约束。希望对您有所帮助。
关于ios - Collection View 单元格的内容大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517114/