【发布时间】:2017-04-07 22:19:26
【问题描述】:
我的 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)
还是不行。我尝试使用 Int 初始化程序返回 CGSize。我已经尝试转换为 Ints 并返回到 CGFloats。似乎没有任何效果。
我已将问题范围缩小到这一点。它与它上面的width 代码(这是一个字符串扩展名)或其他任何东西没有任何关系。
超级奇怪。有人有这方面的经验吗?
编辑:一些图片
顶部是CGSize(width: w, height: 28),其中w 是CGFloat,可以等于128 或任何其他值。底部是CGSize(width: 128, height: 28)
【问题讨论】:
-
评论中的意思是
e.g. 138? -
呃!我知道这个问题,但我不记得解决方案......我会在我知道的时候回来找你!但是有一个解决方案:)
-
@alistra 任何数字,无论是 int 还是 cgfloat
-
@HAS 再保证!期待回音
-
我正在尝试在每个集合视图单元格中实现与文本和潜在图像相对应的宽度,顶部和底部插入 15pt,集合视图单元格之间插入 10pt