我在 Collection View 中使用拖放功能。它工作正常,但是当用户将单元格捕获到另一个位置时替换数组的值时。我已经重新加载 Collection View 。但是当我们拖放单元格 0 和1 Collection View 不会重新加载所有单元格,它只会重新加载一个单元格。
我不知道我的代码有什么问题。 下面是我的代码。
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()
}
}
最佳答案
我也有同样的问题。不知道为什么 reloadData()
在 endInteractiveMovement()
或 cancelInteractiveMovement()
之后不起作用,但我有一个解决方法。
不要使用reloadData()
,而是使用reloadSections()
,例如:
self.collectionView.cancelInteractiveMovement()
// Not working: self.collectionView.reloadData()
UIView.performWithoutAnimation {
self.collectionView.reloadSections(IndexSet(integer: 0))
}
此外,如果您在 DispatchQueue.main.asyncAfter()
中使用 reloadData()
,它也会起作用。
关于ios - Collection View 不会每次都重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47832725/