我有一个UICollectionView
用户可以长按然后移动项目。我已经实施了func invalidationContext(forInteractivelyMovingItems
and func invalidationContextForEndingInteractiveMovementOfItems
方法来处理这个问题。
在 iOS 16 beta 上进行测试时,应用程序在移动项目时崩溃。
根本原因是previousIndexPaths
and targetIndexPaths
在下面的代码中两者都变为 nil。知道为什么会发生这种情况吗?在
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)
}
UICollectionView
移动项目的委托方法
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if self.longPressGesture.state == .ended {
self.collectionView.reloadData()
return
}
let cell = self.availableItems[sourceIndexPath.item]
self.availableItems.remove(at: sourceIndexPath.item)
self.availableItems.insert(cell, at: destinationIndexPath.item)
}
On iOS 16 previousIndexPaths
and targetIndexPaths
are nil
On iOS 15 previousIndexPaths
and targetIndexPaths
are have values