我有一个水平的 Collection View ,每个单元格都有自己的宽度。我使用默认的 UICollectionViewFlowLayout。重新排列时,单元格继承了它在此移动过程中覆盖的单元格的宽度,这是我不想要的。知道如何避免这种行为吗?
最佳答案
因此,如果您的 UICollectionView 具有不同大小的单元格,并且您希望在使用标准 UICollectionViewFlowLayout 移动时保持它们的大小,请使用以下命令:
extension UICollectionViewFlowLayout {
@available(iOS 9.0, *)
open override func invalidationContext(forInteractivelyMovingItems targetIndexPaths: [IndexPath], withTargetPosition targetPosition: CGPoint, previousIndexPaths: [IndexPath], previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forInteractivelyMovingItems: targetIndexPaths, withTargetPosition: targetPosition, previousIndexPaths: previousIndexPaths, previousPosition: previousPosition)
//Check that the movement has actually happeneds
if previousIndexPaths.first!.item != targetIndexPaths.first!.item {
collectionView?.dataSource?.collectionView?(collectionView!, moveItemAt: previousIndexPaths.first!, to: targetIndexPaths.last!)
}
return context
}
open override func invalidationContextForEndingInteractiveMovementOfItems(toFinalIndexPaths indexPaths: [IndexPath], previousIndexPaths: [IndexPath], movementCancelled: Bool) -> UICollectionViewLayoutInvalidationContext {
return super.invalidationContextForEndingInteractiveMovementOfItems(toFinalIndexPaths: indexPaths, previousIndexPaths: previousIndexPaths, movementCancelled: movementCancelled)
}
@available(iOS 9.0, *) //If you'd like to apply some formatting as the dimming of the movable cell
open override func layoutAttributesForInteractivelyMovingItem(at indexPath: IndexPath, withTargetPosition position: CGPoint) -> UICollectionViewLayoutAttributes {
let attributes = super.layoutAttributesForInteractivelyMovingItem(at: indexPath, withTargetPosition: position)
attributes.alpha = 0.8
return attributes
}
在 Controller 的 moveItemAt 方法中,不要忘记检查压力状态是否已更改,例如:
override func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath) {
if #available(iOS 9.0, *) {
if self.longPressureGestureRecognizer.state == .ended {
return
}
//Update your data
data.moveItem(at: sourceIndexPath.row, to: destinationIndexPath.row)
}
}
关于ios - 移动时保持 UICollectionView 中自定义单元格的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44957566/