UICollectionView / FlowLayout
UICollectionView / FlowLayout
我在使用 UICollectionView 和相关布局时遇到了挑战。我正在尝试创建一个包含两列的垂直 UICollectionView,其中左右两列中的单元格的位置如图所示:
我确实成功地创建了两列,但很难在我的布局中找到正确的设置,以使右列偏移一个单元格高度的一半。请注意,根据屏幕宽度(减去间距),所有单元格都具有相同的计算尺寸...
我的数据数组中的每个单元格都有一个位置索引,因此我可以很容易地根据它(奇数/偶数)找出一个单元格是位于右侧还是左侧
非常感谢任何帮助
下面是我将如何实现 UICollectionViewFlowLayout
的子类来实现您想要的。
class OffsetFlowLayout: UICollectionViewFlowLayout {
var verticalOffset: CGFloat = 0
override func prepare() {
super.prepare()
verticalOffset = 100 // Calculate offset here
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attributes = super.layoutAttributesForItem(at: indexPath) else { return nil }
guard remainder(Double(indexPath.row), 2) != 0 else { return attributes }
// For each item in the right column, offset the y value of it's origin
attributes.frame.origin.y += verticalOffset
return attributes
}
}
如您所见,在我们实现 layoutAttributesForItem
时,我们做的第一件事是调用 super 并将值存储在 returns 中。然后我们检查索引,如果我们在左列,我们 return super 给了我们什么,这将是 "default" 值。
如果我们在右列,我们修改属性对象以将单元格的框架移动我们想要的偏移量,然后 return 那一个。
注意:我还没有测试过这个。 UICollectionViewFlowLayout
有可能使用前面的单元格来布局后面的单元格,在这种情况下,您只需要修改右列中的第一个元素,只需将 guard remainder(Double(indexPath.row), 2) != 0 else { return attributes }
更改为 guard indexPath.row == 1 else { return attributes }
我在使用 UICollectionView 和相关布局时遇到了挑战。我正在尝试创建一个包含两列的垂直 UICollectionView,其中左右两列中的单元格的位置如图所示:
我确实成功地创建了两列,但很难在我的布局中找到正确的设置,以使右列偏移一个单元格高度的一半。请注意,根据屏幕宽度(减去间距),所有单元格都具有相同的计算尺寸...
我的数据数组中的每个单元格都有一个位置索引,因此我可以很容易地根据它(奇数/偶数)找出一个单元格是位于右侧还是左侧
非常感谢任何帮助
下面是我将如何实现 UICollectionViewFlowLayout
的子类来实现您想要的。
class OffsetFlowLayout: UICollectionViewFlowLayout {
var verticalOffset: CGFloat = 0
override func prepare() {
super.prepare()
verticalOffset = 100 // Calculate offset here
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attributes = super.layoutAttributesForItem(at: indexPath) else { return nil }
guard remainder(Double(indexPath.row), 2) != 0 else { return attributes }
// For each item in the right column, offset the y value of it's origin
attributes.frame.origin.y += verticalOffset
return attributes
}
}
如您所见,在我们实现 layoutAttributesForItem
时,我们做的第一件事是调用 super 并将值存储在 returns 中。然后我们检查索引,如果我们在左列,我们 return super 给了我们什么,这将是 "default" 值。
如果我们在右列,我们修改属性对象以将单元格的框架移动我们想要的偏移量,然后 return 那一个。
注意:我还没有测试过这个。 UICollectionViewFlowLayout
有可能使用前面的单元格来布局后面的单元格,在这种情况下,您只需要修改右列中的第一个元素,只需将 guard remainder(Double(indexPath.row), 2) != 0 else { return attributes }
更改为 guard indexPath.row == 1 else { return attributes }