![](/img/trans.png)
[英]IOS UICollectionView insertItemsAtIndexPaths crash when header is on screen
[英]UICollectionView crash when moving items on iOS 16 beta
我有一个UICollectionView
,用户可以在其中长按然后移动项目。 我已经实现了func invalidationContext(forInteractivelyMovingItems
和func invalidationContextForEndingInteractiveMovementOfItems
方法来处理这个问题。
在 iOS 16 beta 上进行测试时,移动项目时应用程序崩溃。 根本原因是previousIndexPaths
和targetIndexPaths
在下面的代码中都变成了 nil。 知道为什么会这样吗? 在 < iOS16 上工作正常。
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)
}
只需添加一个延迟,它现在就可以在 iOS 16 上为我工作。
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.