集合视图单元格宽度不正确
Posted
技术标签:
【中文标题】集合视图单元格宽度不正确【英文标题】:collection view cell width is not correct 【发布时间】:2018-09-24 15:07:22 【问题描述】:更新到 ios 12 和 xcode 10 后,带有单元格大小的 collectionView 不再正常工作。
我在 xcode 中有这个布局
景色是这样的。
这就是现在的样子。
我已尝试将collectionview 视图设置为宽度约束并在
中进行了修改 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
cell.widthConstraint.constant = UIScreen.main.bounds.width / 3
但什么也没发生。
【问题讨论】:
【参考方案1】:您使用错误的方法设置单元格大小。
而不是collectionView(_:cellForItemAt:)
使用collectionView:layout:sizeForItemAtIndexPath:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
let itemHeight = 60
let itemWidth = UIScreen.main.bounds.width / 3
return CGSize(width: itemWidth, height: itemHeight)
此外,您可以使用Interface Builder
s Size Inspector
设置项目大小,但在这种情况下,单元格的大小将是绝对的。如果你希望它是屏幕宽度的1/3
,你需要使用布局委托。
【讨论】:
以上是关于集合视图单元格宽度不正确的主要内容,如果未能解决你的问题,请参考以下文章
当单元格具有动态宽度时,CollectionView 中的间距不正确?