-1

用户的任务是按顺序排列单元格。(例如一个孩子)

图片

使用以下方法移动单元格:

    override func viewDidLoad() {
    super.viewDidLoad()
    ...
    table.dragDelegate = self
    table.dropDelegate = self
    table.dragInteractionEnabled = true
    ...
}

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    usersChooseOrder.insert(usersChooseOrder.remove(at: sourceIndexPath.row), at: destinationIndexPath.row)
}
    
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
    print("itemsForBeginning")
    return []
}
    
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
    print("  coordinator")
}

在任何时候,您都可以通过按“完成”按钮和正确的单元格来检查放置的正确性,它们所在的位置是绿色的。告诉我在哪个方向上实现以下目标:

绿色单元格应固定到位,不再移动,无论是用手指还是由于其他单元格的移动。那些。如果将 5 移动到 4 下的位置 2,则 2 应移至位置 6,而 4 应保留在原位。如果我们将 5 移到 6 上,那么 6 和 1 会上升到 4 之上,并且 5 会出现在 4 之上。

我会很高兴任何提示。

谢谢!

4

1 回答 1

0

绿色单元格应固定到位,不再移动

检查canMoveRowAt绿色单元格的索引并返回 false:

if indexPath.row == indexOfGreenCell{
   return false
} else {
   return true
}

其余使用此功能。请注意,您必须对其进行编辑以使绿色项目保持静止。

    func refreshIndex( sourceIndexPath: IndexPath, destinationIndexPath: IndexPath){
        let source = sourceIndexPath.row //Item to move
        let destination = destinationIndexPath.row //destination
        
        if source < destination {
            var startIndex = source + 1
            let endIndex = destination
            var startOrder = (numbers[source])
            while startIndex <= endIndex {
                numbers[startIndex] = startOrder
                startOrder = startOrder + 1
                startIndex = startIndex + 1
                
            }
            
            numbers[source] = startOrder
            
        } else if destination < source {
            var startIndex = destination
            let endIndex = source
            var startOrder = (numbers[destination]) + 1
            let newOrder = numbers[destination]
            while startIndex <= endIndex {
                numbers[startIndex] = startOrder
                startOrder = startOrder + 1
                startIndex = startIndex + 1
            }
            numbers[source] = newOrder
        }
    }

在以下函数中调用它:

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {}
于 2020-12-18T14:47:03.240 回答