我的UICollectionView和我的sizeForItemAtIndexPath
函数中有可变宽度,我最终返回CGSize
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var width: CGFloat = indexPath.row == 0 ? 37 : 20 // default paddings based on spacing in cell
let font = UIFont.systemFont(ofSize: 14, weight: UIFontWeightRegular)
if indexPath.row == 0 {
width += listingsFilter.stringValue.width(withConstrainedHeight: 28, font: font)
} else {
let string = viewModel.valueRangeForButton[indexPath.row - 1]
width += string.width(withConstrainedHeight: 28, font: font)
}
print(width) // some decimal e.g. 138.1239581
let w: CGFloat = width.rounded() // rounded e.g. 13
return CGSize(width: w, height: 28)
}
如果我使用宽度数字(例如128)来存储返回值,而不是拥有变量,则集合视图会尊重UIEdgeInsets
。如果我使用宽度变量返回CGSize
,则UIEdgeInsets
将被忽略,除了第一个和最后一个元素。
我觉得我发现了一些很深的CoreGraphics
错误。
对于最后两行,如果我将它们更改为
let x: CGFloat = 128 // or 128.0, doesn't matter
return CGSize(width: x, height: 28)
它仍然无法运作。我尝试使用CGSize
初始化程序返回Int
。我试过去Ints并回到CGFloat
。似乎没什么用。
我已经将问题缩小到了这一点。它与上面的width
代码(字符串扩展名)或其他任何内容都没有任何关系。
超级怪异。有人有这方面的经验吗?
修改:部分图片
排名第一的是CGSize(width: w, height: 28)
,其中w
是CGFloat
,可以等于128或其他任何值。底部是CGSize(width: 128, height: 28)
答案 0 :(得分:0)
UICollectionViewDelegateFlowLayout
。它继承自UICollectionViewDelegate
。这应该成功。 答案 1 :(得分:0)
我可以从op的问题中了解
在您需要的单元格内移动内容
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout:
UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 15, left: 0, bottom: 15, right: 0)
}
在您需要的各个单元格之间移动空格
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
return 15
}
确保您面对代理UICollectionViewDelegateFlowLayout
答案 2 :(得分:0)
我从未尝试过返回硬编码值而不是sizeForItemAtIndexPath()
中的变量,我一直认为UIEdgeInsets
甚至不会影响UICollectionView
的单元格之间的间距1}},但只包括整个细胞区域周围的空间。看起来UIEdgeInsets
并不打算影响单元格之间的间距,在这种情况下,Apple的错误与它看起来相反 - UIEdgeInsets
奇怪地影响一个异常值中单元格之间的间距实际上,在任何情况下,它从未打算这样做。这个红鲱鱼让你有理由认为必须有一种可靠的编程方式让UIEdgeInsets
设置UICollectionView
个单元格之间的间距。我还没有找到一种程序化的方法。当我找到以下故事板解决方案时,我不再寻找一个。
花了很多时间调整UICollectionViews
以使它们看起来像我想要的那样,我发现设置单元格间距的唯一可靠方法是使用如下的故事板设置:
在故事板中,选择您的UICollectionView
,转到属性检查器,找到“Min Spacing”部分,然后在“For Cells”框中键入您想要的值(在您的情况下,10) )。 “For Cells”值是单元格之间的水平间距。对“For Lines”值执行相同操作,该值是单元格之间的垂直间距。
答案 3 :(得分:0)
答案 4 :(得分:-1)
它与UIEdgeInsets
无关,它与您在代码中计算的width
有关。设置width: 128
时,为单元格提供的宽度大于实际需要的宽度(假设为90),因此根据UICollectionViewCell
的设计,它可能感觉每个单元格都有一个UIEdgeInsets
。
如果你正在使用IB,你可以从IB设置cellSpacing
和lineSpacing
,否则你必须实现UICollectionViewDelegateFlowLayout