moveRowAt 使用 Realm 重新排序 TableView

moveRowAt Reorder TableView with Realm

我有 Realm 模型:

class ShoppingListItem: Object {
    @objc dynamic var department: String = ""
    var item = List<ShoppingItem>()
}

class ShoppingItem: Object {
    @objc dynamic var name: String = ""
    @objc dynamic var checked: Bool = false
    @objc dynamic var sortingIndex = 0
}

我尝试添加功能以重新排序 tableView 的行。这是我的代码:

var shoppingList: Results<ShoppingListItem>!

func numberOfSections(in tableView: UITableView) -> Int {
    return shoppingList?.count ?? 0
    }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return shoppingList[section].item.count
}
    
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ShoppingCell", for: indexPath)
    
    let oneItem = shoppingList[indexPath.section].item[indexPath.row]
    cell.textLabel?.text = oneItem.name
    
    if oneItem.checked {
        cell.imageView?.image = UIImage(systemName: "app.fill")
  } else {
    cell.imageView?.image = UIImage(systemName: "app")
  }
    
    return cell
}

我应该向函数 moveRowAt 添加什么才能重新排序行?这是代码示例。我应该如何修改它以使其与 Realm 一起工作?

 func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
            let moved = shoppingList[sourceIndexPath.section].item[sourceIndexPath.row]


            shoppingList[sourceIndexPath.section].item.remove(at: sourceIndexPath.row)
            shoppingList[destinationIndexPath.section].item.insert(moved, at: destinationIndexPath.row)

        }

关于 Realm List 对象的一个​​很酷的事情是它们保持它们的顺序。

在这种情况下,您不需要 sortingIndex 属性,因为这些项目存储在列表中。

class ShoppingListItem: Object {
    @objc dynamic var department: String = ""
    var item = List<ShoppingItem>() <- order is maintained
}

当您对 tableView 中的行重新排序时,通过将其插入新位置并将其从旧位置删除来反映列表中的更改(首先完成取决于对象移动的方向) .您可以使用 .insert 和 .remove

手动完成
itemList.remove(at: 5) //remove the shoppingItem object at index 5
itemList.insert(shoppingItem, at: 1) //insert the object at index 1

或者使用超级简单的 .move 将对象从一个索引移动到另一个索引。

itemList.move(from: 5, to: 1)