Swift:无法长按拖动单元格到 UICollectionViewController 和 UITableView 中的空部分

Nei*_*eil 4 drag-and-drop uitableview ios uicollectionview swift

以前,我尝试用 UITableView 中的长按拖动来替换标准的苹果重新排序控件(从右侧手柄拖动单元格)。然而,由于某种原因,通过长按拖动,我无法将单元格移动到其中已经没有单元格的部分。现在我正在尝试实现一个功能,用户可以在 UICollectionViewController 而不是 UITableView 中的两个部分之间拖动单元格。我实现了长按拖动功能,但由于某种原因我遇到了同样的问题。我如何向这些部分添加一个虚拟单元,以便它们永远不为空,或者是否有更好的方法来解决这个问题?还有一种方法可以拖动单元格而无需长按?

这些是我添加到 UICollectionViewController 类中以启用长按拖动的函数:

override func viewDidLoad() {
    super.viewDidLoad()

    let longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongGesture:")
    self.collectionView!.addGestureRecognizer(longPressGesture)
}

func handleLongGesture(gesture: UILongPressGestureRecognizer) {

    switch(gesture.state) {

    case UIGestureRecognizerState.Began:
        guard let selectedIndexPath = self.collectionView!.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else {
            break
        }
        collectionView!.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)
    case UIGestureRecognizerState.Changed:
        collectionView!.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!))
    case UIGestureRecognizerState.Ended:
        collectionView!.endInteractiveMovement()
    default:
        collectionView!.cancelInteractiveMovement()
    }
}

override func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

    let fromRow = sourceIndexPath.row
    let toRow = destinationIndexPath.row
    let fromSection = sourceIndexPath.section
    let toSection = destinationIndexPath.section

    var item: Item
    if fromSection == 0 {
        item = section1Items[fromRow]
        section1Items.removeAtIndex(fromRow)
    } else {
        item = section2Items[sourceIndexPath.row]
        section2Items.removeAtIndex(fromRow)
    }

    if toSection == 0 {
        section1Items.insert(score, atIndex: toRow)
    } else {
        section2Items.insert(score, atIndex: toRow)
    }
}

override func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Vas*_*huk 5

细节

  • Xcode 10.2 (10E125)、Swift 5、来自 iOS 11

主意

我想建议处理

func collectionView(_ collectionView: UICollectionView, dragSessionWillBegin session: UIDragSession) {...}
func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) {...}
Run Code Online (Sandbox Code Playgroud)

当您开始拖动时,您可以将临时单元添加到空(或所有)部分的末尾。而且你的空部分不会是空的)。然后你可以使用标准 UIKit api 删除你的单元格。在拖动结束之前,您可以删除临时单元格。

为什么?

我不建议使用手势处理程序,因为:

  1. “制造自行车”的大好机会
  2. 该解决方案可能非常耗时且维护起来困难/昂贵。
  3. 用于使用经过更深入测试的表/集合的标准 API

样本

拖放的完整示例

在此输入图像描述

更多信息