集合视图。 Item 之间的最大距离。 Swift 3
CollectionView. Maximum distance between Item. Swift 3
我知道项目之间只有最小间距,您可以通过尺寸检查器或
实现
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
确实在 SE 的模拟器上,我的项目如下图所示。
但是当我 运行 在更大的模拟器上时,我的单元格项目之间的距离正在增加并且没有按预期显示。
有什么方法可以设置它们之间的最大尺寸吗?
从逻辑上讲,在集合视图中设置项目之间的 space 时,还有一个因素需要牢记,即单元格的 大小 .如果您按原样获取单元格(具有默认大小)-我的假设是您的情况-,它将在集合视图中静态出队,即单元格的大小将保持原样。
所以,你应该做的是通过符合
UICollectionViewDelegateFlowLayout
and implementing collectionView(_:layout:sizeForItemAt:)
:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// let's assume that each row in the collection view should contains 3 cells:
let desiredWidth = collectionView.frame.width / 3
// height is also equals to the width to be a square...
return CGSize(width: desiredWidth, height: desiredWidth)
}
此时,如果您将项目之间的最小值 space 设置为零,则每行应包含三个单元格,它们之间没有 space。
如果您打算在单元格之间设置一点 space,您应该在声明单元格所需的宽度时反映出来,例如:
// since each row contains 3 cells, subtracting 2 from each cell width
// means it would be 6 points (3 * 2) divided at the whole row (2 spaces, 3 points for each)
let desiredWidth = collectionView.frame.width / 3 - 2
我知道项目之间只有最小间距,您可以通过尺寸检查器或
实现func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
确实在 SE 的模拟器上,我的项目如下图所示。
但是当我 运行 在更大的模拟器上时,我的单元格项目之间的距离正在增加并且没有按预期显示。
有什么方法可以设置它们之间的最大尺寸吗?
从逻辑上讲,在集合视图中设置项目之间的 space 时,还有一个因素需要牢记,即单元格的 大小 .如果您按原样获取单元格(具有默认大小)-我的假设是您的情况-,它将在集合视图中静态出队,即单元格的大小将保持原样。
所以,你应该做的是通过符合
UICollectionViewDelegateFlowLayout
and implementing collectionView(_:layout:sizeForItemAt:)
:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// let's assume that each row in the collection view should contains 3 cells:
let desiredWidth = collectionView.frame.width / 3
// height is also equals to the width to be a square...
return CGSize(width: desiredWidth, height: desiredWidth)
}
此时,如果您将项目之间的最小值 space 设置为零,则每行应包含三个单元格,它们之间没有 space。
如果您打算在单元格之间设置一点 space,您应该在声明单元格所需的宽度时反映出来,例如:
// since each row contains 3 cells, subtracting 2 from each cell width
// means it would be 6 points (3 * 2) divided at the whole row (2 spaces, 3 points for each)
let desiredWidth = collectionView.frame.width / 3 - 2