我在集合视图中使用拖放功能。工作正常,但是当用户将单元格陷入另一个位置时替换数组的值。我重新加载集合视图。但是当我们拖放单元格0和1个集合视图不会重新加载所有单元格,只重新加载一个单元格。
我不知道我的代码中有什么问题。 以下是我的代码。
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
collection_view.addGestureRecognizer(longPressGesture)
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell_images", for: indexPath) as! AddImagesCollectionViewCell
cell.layer.borderWidth=1
if Details.Images[indexPath.item].sourceType == sourceType.URL
{
cell.img_images.downloadedFrom(link: Details.Images[indexPath.item].imageURL!, contentMode: .scaleAspectFill)
}
else
{
cell.img_images.image = Details.Images[indexPath.item].image
}
Details.Images[indexPath.row].sequence="\(indexPath.row + 1)"
return cell
}
func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool
{
if indexPath.row == Details.Images.count
{
return false
}
return true
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
{
print("Starting Index: \(sourceIndexPath.item)")
print("Ending Index: \(destinationIndexPath.item)")
let tempArray = Details.Images[sourceIndexPath.item]
Details.Images.remove(at: sourceIndexPath.item)
Details.Images.insert(tempArray, at: destinationIndexPath.item)
collectionView.reloadData()
}
@objc func handleLongGesture(gesture: UILongPressGestureRecognizer)
{
switch(gesture.state)
{
case .began:
guard let selectedIndexPath = collection_view.indexPathForItem(at: gesture.location(in: collection_view))
else
{
break
}
if !(selectedIndexPath.row == Details.Images.count)
{
collection_view.beginInteractiveMovementForItem(at: selectedIndexPath)
}
case .changed:
guard let selectedIndexPath = collection_view.indexPathForItem(at: gesture.location(in: collection_view))
else
{
break
}
if !(selectedIndexPath.row == Details.Images.count)
{
collection_view.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
}
case .ended:
collection_view.endInteractiveMovement()
default:
collection_view.cancelInteractiveMovement()
}
}
答案 0 :(得分:2)
你的代码中没有bug,collectionView只会重新加载一个单元格(你已经放弃了一个单元格)。如果你想重新加载所有的集合视图,你需要在endInteractiveMovement()
之后调用reloadData()。
答案 1 :(得分:0)
我有同样的问题。不知道为什么reloadData()
或endInteractiveMovement()
之后cancelInteractiveMovement()
无法工作,但是我有解决方法。
使用reloadData()
代替reloadSections()
,例如:
self.collectionView.cancelInteractiveMovement()
// Not working: self.collectionView.reloadData()
UIView.performWithoutAnimation {
self.collectionView.reloadSections(IndexSet(integer: 0))
}
此外,如果您在reloadData()
中使用DispatchQueue.main.asyncAfter()
,它将起作用。
答案 2 :(得分:0)
我存在通过拖放进行重新排序的问题-收集视图不会重新加载由于移动操作而位置发生变化的所有单元格。我在实现moveItemAtIndexPath:toIndexPath:
时调用了performDropWithCoordinator
来解决了这个问题。参见this question。