class YourViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
// ... 其他代码 ...
var pendingUpdates: [() -> Void] = []
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedItem = indexPath.item
if selectedItems.count < 2 && !selectedItems.contains(selectedItem) {
// Execute loading animation and network request here
// Simulate network request completion
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
// Update data source and add refresh operation to the pendingUpdates
self.selectedItems.insert(selectedItem)
self.pendingUpdates.append {
self.moveSelectedItemAtFront(selectedItem)
}
self.processPendingUpdates()
}
} else if selectedItems.count == 2 && !selectedItems.contains(selectedItem) {
// Execute loading animation and network request here
// Simulate network request completion
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
// Update data source and add refresh operation to the pendingUpdates
let secondSelectedItem = self.selectedItems.sorted()[1]
self.selectedItems.remove(secondSelectedItem)
self.selectedItems.insert(selectedItem)
self.pendingUpdates.append {
self.moveSelectedItemAtFront(selectedItem)
}
self.processPendingUpdates()
}
}
}
func processPendingUpdates() {
guard !pendingUpdates.isEmpty else { return }
collectionView.performBatchUpdates({
for update in pendingUpdates {
update()
}
pendingUpdates.removeAll()
}, completion: nil)
}
}