Skip to content

Instantly share code, notes, and snippets.

@SunXiaoShan
Created April 22, 2020 03:08
Show Gist options
  • Save SunXiaoShan/ac8fd4435a3fc956a19f48fdfc5b6c2f to your computer and use it in GitHub Desktop.
Save SunXiaoShan/ac8fd4435a3fc956a19f48fdfc5b6c2f to your computer and use it in GitHub Desktop.
class ViewController: UIViewController {
func setupCollectionView() {
self.collectionView.collectionViewLayout = columnLayout
self.collectionView.dataSource = self
self.collectionView.dragInteractionEnabled = true
self.collectionView.dragDelegate = self
self.collectionView.dropDelegate = self
}
func updateDataIndex(from fromIndexPath: IndexPath, to toIndexPath: IndexPath) {
let fromPosition = fromIndexPath.item
let toPosition = toIndexPath.item
let selected = cellDataList[fromPosition] as Int
DispatchQueue.main.async {[weak self] in
self?.cellDataList.remove(at: fromPosition)
self?.cellDataList.insert(selected, at: toPosition)
self?.collectionView.reloadData()
UIView.performWithoutAnimation {
self?.collectionView.reloadSections(IndexSet(integersIn: 0...0))
}
}
}
}
extension ViewController: UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
if (collectionView.hasActiveDrag) {
if let destinationIndexPath = coordinator.destinationIndexPath {
updateDataIndex(from: coordinator.items.first!.sourceIndexPath!, to: destinationIndexPath)
}
}
}
func collectionView(_ collectionView: UICollectionView,
dropSessionDidUpdate session: UIDropSession,
withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment