动画UITableViewCell以编程方式移动到底部

时间:2017-05-15 15:01:02

标签: ios swift tableview

我在同一部分有一组单元格。当我按下其中一个单元格上的按钮时,我希望它移动到底部,带有动画,移动到其他单元格上。我想到的动画类似于在编辑模式下拖动单元格时发生的动画,但我希望在点击按钮时以编程方式完成。 对于我收集的内容,我应该使用tableView.moveRowAtIndexPath,但我似乎无法正确地做到这一点:

 //inside the function for when the button is pressed
 let cell = sender.superview?.superview?.superview as! MainTableViewCell
 let indexPath = tableView.indexPathForCell(cell)
 let goal = goals[(indexPath?.row)!]

 goals.removeAtIndex((indexPath?.row)!)
 goals.append(goal)

 tableView.beginUpdates()
 self.tableView.moveRowAtIndexPath(indexPath!, toIndexPath: indexPaths.last!)
 tableView.endUpdates()

 tableView.reloadData()

此后,该功能会禁用触发功能本身的按钮。我注意到的事情是,不仅我要移动的单元格被禁用,而且该部分中的最后一个单元格也会被禁用。如果最后一个单元格已被禁用,则最后一个单元格被禁用,依此类推。 任何帮助将不胜感激。

编辑:我也打电话给canMoveRowAtIndexPath并返回true。

2 个答案:

答案 0 :(得分:2)

如果你打电话给tableView.reloadData(),你的动画会失去动画效果。您应该只能移动单元格,然后更新数据源(goals数组)以反映项目的新顺序。您也无需致电tableView.beginUpdates()tableView.endUpdates()进行单次更新。您可以使用这些调用批量处理多个更新(插入,删除,移动等)

//inside the function for when the button is pressed
 let cell = sender.superview?.superview?.superview as! MainTableViewCell
 let indexPath = tableView.indexPathForCell(cell)
 let goal = goals[(indexPath?.row)!]

 tableView.moveRowAtIndexPath(indexPath!, toIndexPath: indexPaths.last!)
 goals.removeAtIndex((indexPath?.row)!)
 goals.append(goal)

我创建了一个简单的测试项目来验证,使用简单的字符串作为数据项,并且动画效果按预期工作。请点击此处:MoveTableRow

答案 1 :(得分:0)

我这样做是

UIView.transition(with: tableView, duration: 0.35, options: .transitionCrossDissolve, animations: { self.tableView.moveRow(at: indexPath, to: indexPath.last) })

要移到开头:

UIView.transition(with: tableView, duration: 0.35, options: .transitionCrossDissolve, animations: { self.tableView.moveRow(at: indexPath, to: [0,0]) })
相关问题