简体   繁体   中英

Collection view beginInteractiveMovementForItem returns false

I'm using collection view and want to move cells when user paned. This is the code.

func longPressPhotoCollectionView(sender: UILongPressGestureRecognizer) {
    guard isEditing else {
        return
    }
    let point = sender.location(in: photoCollectionView)
    switch sender.state {
    case .began:
        guard let indexPath = photoCollectionView.indexPathForItem(at: point) else {
            return
        }
        let isS = photoCollectionView.beginInteractiveMovementForItem(at: indexPath)
        print(isS)
    case .changed:
        photoCollectionView.updateInteractiveMovementTargetPosition(point)
    case .ended:
        photoCollectionView.endInteractiveMovement()
    default:
        photoCollectionView.cancelInteractiveMovement()
    }
}

I doubt custom layout will cause this problem. And I found this from Apple's Doc.

When you call this method, the collection view consults its delegate to make sure the item can be moved. If the data source does not support the movement of the item, this method returns false.

I don't know how to handle animations, especially with custom layout. Please help me! Thanks!

Implement the following in your UICollectionViewDataSource:

func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {

    print("MOVING!")
    // Switch the Items in the DataSource
}

When you call this method, the collection view consults its delegate to make sure the item can be moved. If the data source does not support the movement of the item, this method returns false.

The Apple documentation is misleading. It seems to imply that you should override some method on UICollectionViewDelegate to make a cell movable. In fact, it's a UICollectionViewDataSource method:

optional func collectionView(_ collectionView: UICollectionView, 
               canMoveItemAt indexPath: IndexPath) -> Bool

https://developer.apple.com/documentation/uikit/uicollectionviewdatasource/1618015-collectionview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM