【发布时间】:2019-11-05 14:43:39
【问题描述】:
我正在尝试实现两个collectionViews,在它们之间拖放单元格。但是我在collectionView中重新排序单元格时遇到了奇怪的行为。这是复制该行为的最少代码。
提供的代码按预期工作,但我取消注释 collectionView.dropDelegate = self 它不再工作。我试图找到UICollectionViewDropDelegate 的哪个方法被调用,但没有一个被调用。
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
print("in drop")
}
@IBOutlet weak var collectionView: UICollectionView!
var items = [UIColor.red, UIColor.green, UIColor.blue]
override func viewDidLoad() {
super.viewDidLoad()
// collectionView.dropDelegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.contentView.layer.backgroundColor = items[indexPath.item].cgColor
return cell
}
func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let temp = items.remove(at: sourceIndexPath.item)
items.insert(temp, at: destinationIndexPath.item)
}
@IBAction func handleLongGesture(_ gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
guard let selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
break
}
self.collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case .changed:
self.collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case .ended:
self.collectionView.endInteractiveMovement()
default:
self.collectionView.cancelInteractiveMovement()
}
}
}
所以发生了这种情况,我应该怎么做才能让dragDelegate 表现正常?
【问题讨论】:
-
尝试参考本教程 - hackernoon.com/…
-
谢谢,我看到了。这是一个解决方案,但对于复杂的对象(我的意思是,如果单元格不是简单的图像,而是一堆文本、图像和其他数据),它需要额外的努力,而使用 collectionView 重新排序(没有 dragDelegate)会开箱即用。
标签: ios swift uicollectionview drag-and-drop swift4