我需要在纵向模式下保持 UICollectionViewCell 居中对齐。
最终结果应该是这样的:
animation
我正在使用此代码来执行此操作:
override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var layoutAttributes: Array = layoutAttributesForElements(in: collectionView!.bounds)!
if layoutAttributes.count == 0 {
return proposedContentOffset
}
var firstAttribute: UICollectionViewLayoutAttributes = layoutAttributes[0]
for attribute: UICollectionViewLayoutAttributes in layoutAttributes {
if attribute.representedElementCategory != .cell {
continue
}
if((velocity.x >= 0.0 && attribute.center.x > firstAttribute.center.x) ||
(velocity.x <= 0.0 && attribute.center.x < firstAttribute.center.x)) {
firstAttribute = attribute;
}
}
return CGPoint(x: firstAttribute.center.x -
collectionView!.bounds.size.width * 0.5, y: proposedContentOffset.y)
}
这适用于所有单元格,除了最后一个单元格在滚动时没有居中对齐。
实际结果:
有什么办法可以解决这个问题吗?
最佳答案
我发现如果我设置
collectionView.isPagingEnabled = true
它会破坏中心单元格设置。一旦我将其关闭,一切又恢复正常了
关于ios - "targetContentOffset"UICollectionViewFlowLayout 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45614617/