使用动画重新加载表格视图单元格(Swift)

时间:2015-04-14 16:20:09

标签: ios swift row tableview reloaddata

有没有办法重新加载具有动画的多个部分的特定UITableView单元格?

我一直在使用:

self.TheTableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Right)

这会激活该部分中的所有单元格。另一种选择是使用:

self.TheTableView.reloadRowsAtIndexPaths(<#indexPaths: [AnyObject]#>, 
                                         withRowAnimation: <#UITableViewRowAnimation#>)

编辑:

使用reloadRowsAtIndexPaths后

由于未捕获的异常终止应用程序&#39; NSInternalInconsistencyException&#39;,原因:&#39;无效更新:第1部分中的无效行数。更新后现有部分中包含的行数(5)必须等于更新前的该部分中包含的行数(4),加上或减去从该部分插入或删除的行数(0插入,0删除)和加或减移入的行数或超出该部分(0移入,0移出)。&#39;

尝试通过将对象附加到数组中来找到重新加载tableview的平滑方法。

在reloadRowsAtIndexPaths工作之前调用TheTableView.reloadData(),但动画很糟糕。还有另一种方法吗?

3 个答案:

答案 0 :(得分:11)

为什么不直接重新加载细胞? indexPath包含节和行,因此只需跟踪要重新加载的节,并填充该数组中的索引。

var indexPath1 = NSIndexPath(forRow: 1, inSection: 1)
var indexPath2 = NSIndexPath(forRow: 1, inSection: 2)
self.tableView.reloadRowsAtIndexPaths([indexPath1, indexPath2], withRowAnimation: UITableViewRowAnimation.Automatic)

根据您的评论,您希望更改数组并在更改中使tableView具有动画效果。如果是这种情况,您应该考虑对UITableViews甚至是NSFetchedResultsController使用beginUpdates()和endUpdates(),以便它可以干净地处理所有更新动画。

self.tableView.beginUpdates()
// Insert or delete rows
self.tableView.endUpdates()

如果您使用核心数据,我建议您使用NSFetchedResultsController,因为它简化了整个过程。否则,您必须自己处理更改。换句话说,如果您的阵列发生更改,则需要使用beginUpdates()和endUpdates()在tableview中手动删除或插入行。 如果您没有使用核心数据,请研究this以了解它是如何处理的。

答案 1 :(得分:4)

在Swift 3.0中

我们可以在tableview中重新加载特定部分的特定行

let indexPath = IndexPath(item: 2, section: 0)
self.tableView.reloadRows(at: [indexPath], with: .automatic)

答案 2 :(得分:2)

官方文档中的 IndexSet

  

管理Set整数值,这些值通常用作索引   输入Cocoa API。有效整数值的范围是   in(0,INT_MAX-1)。超出此范围的任何内容都是错误的。

所以IndexSet是关于索引设置的,只是在[]

中放入一些Int值
// for reload one section
tableView.reloadSections([section], with: .automatic)
// or using like this
tableView.reloadSections(IndexSet(integer: section), with: .automatic)

// for reload multi sections
tableView.reloadSections([1, 2, 3, section], with: .automatic)