ios - 移动时保持 UICollectionView 中自定义单元格的大小

标签 ios swift uicollectionview uicollectionviewlayout

我有一个水平的 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/

相关文章:

android - 在 iOS 和 Android 上唯一标识 Beacon

ios - Swift中使用自定义分段控件时CollectionCell数据显示问题

ios - 自动调整 UICollectionView 高度以调整其内容大小

ios - 键盘出现时弹出 View 箭头移动

ios - 下面提到的 NSStrings 分配的保留计数是多少

IOS应用加密

iOS Swift - 有没有办法将 subview 添加到表格单元格中并正确定位它?

ios - Siri 建议的网站 favicon

swift - 游戏套件 : NPC element is going to very high floating number coordinates and back on update

ios - 单元格标签文本在单元格中重叠