我有一个集合视图,“每页”有3个视图。滚动时,我需要移动这3个单元格,然后转到下一个“页面”。例如,如果我有4个单元格并滚动集合视图,则需要将集合移至一个配置,在该配置中我只能看到接下来的3个Itens,在这种情况下,只能看到项目4,因为没有项目5和6我正在尝试使用自定义的FlowLayout,但它无法正常工作。
class CustomFlowLayout: UICollectionViewFlowLayout {
var mostRecentOffset: CGPoint = CGPoint()
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint,
withScrollingVelocity velocity: CGPoint) -> CGPoint {
if velocity.x == 0 {
return mostRecentOffset
}
if let cv = self.collectionView {
let cvBounds = cv.bounds
let halfWidth = cvBounds.size.width * 0.5
if let attributesForVisibleCells = self.layoutAttributesForElements(in: cvBounds) {
var candidateAttributes: UICollectionViewLayoutAttributes?
for attributes in attributesForVisibleCells {
if attributes.representedElementCategory != UICollectionElementCategory.cell {
continue
}
if (attributes.center.x == 0) || (attributes.center.x > (cv.contentOffset.x + halfWidth) && velocity.x < 0) {
continue
}
candidateAttributes = attributes
}
if proposedContentOffset.x == -(cv.contentInset.left) {
return proposedContentOffset
}
guard candidateAttributes != nil else {
return mostRecentOffset
}
mostRecentOffset = CGPoint(x: floor(candidateAttributes!.center.x - halfWidth), y: proposedContentOffset.y)
return mostRecentOffset
}
}
mostRecentOffset = super.targetContentOffset(forProposedContentOffset: proposedContentOffset)
return mostRecentOffset
}
}