ios - 在部分之间移动时 MoveRow 方法没有动画

标签 ios swift uitableview

我正在创建购物 list 应用程序。我使用 2 个部分来分隔已购买的元素和未购买的元素。我使用 moveRow 方法在所述两个部分之间移动行。这是移动行的代码。

if indexPath.section == 0 {
    self.shoppingItems.remove(at: indexPath.row)
    self.shoppingItemsBought.append(item)
    self.tableView.beginUpdates()

    let fromIndexPath = NSIndexPath(row: indexPath.row, section: 0)
    let toIndexPath = NSIndexPath(row: 0, section: 1)

    self.tableView.moveRow(at: fromIndexPath as IndexPath, to: toIndexPath as IndexPath)
    self.tableView.endUpdates()

} else {
    self.shoppingItemsBought.remove(at: indexPath.row)
    self.shoppingItems.append(item)
    self.tableView.beginUpdates()

    let fromIndexPath = NSIndexPath(row: indexPath.row, section: 1)
    let toIndexPath = NSIndexPath(row: 0, section: 0)

    self.tableView.moveRow(at: fromIndexPath as IndexPath, to: toIndexPath as IndexPath)
    self.tableView.endUpdates()
 }

行更改其位置,但没有动画。我错过了什么?

最佳答案

一种选择是在 moveRow 周围使用 CATransaction。将您的更改放入 CATransaction block 中,完成后强制重新加载。这将通过动画重新加载。

示例:

CATransaction.begin()
CATransaction.setCompletionBlock {
    tableView.reloadData()
}

tableView.beginUpdates()

// Update the datasource
if indexPath.section == 0 {
    self.shoppingItems.remove(at: indexPath.row)
    self.shoppingItemsBought.append(item)
}
else {
    self.shoppingItemsBought.remove(at: indexPath.row)
    self.shoppingItems.append(item)
}

// Get new IndexPath (indexPath is the old one, as in current)
let newIndexPath = IndexPath(row: 0, section: indexPath.section == 0 ? 1 : 0)

// Move the row in tableview
tableView.moveRow(at: indexPath, to: newIndexPath)

tableView.endUpdates()
CATransaction.commit()

关于ios - 在部分之间移动时 MoveRow 方法没有动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57295652/

相关文章:

iphone - 在 iOS 上绘制带阴影的矩形

ios UIAlertView : make alert wait for my response

ios - 如何以编程方式更新约束并解决登录屏幕的键盘问题

swift - 如何为仅在测试中可见的结构创建 init 方法?

swift - 在 willDisplay 中配置自调整大小的单元格

ios - 将 segue 添加到动态创建的单元格

ios - 游戏中心 : "The connection to service named com.apple.gamed was interrupted"

iphone - 澄清 UITableViewCell 在突出显示事件上的未记录行为

ios - UITableViewController 和 UIColor 滚动时改变位置

ios - 更改导航栏标题字体 - swift