首页 > 解决方案 > moveRowAt 使用 Realm 重新排序 TableView

问题描述

我有领域模型:

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)

        }

标签: iosswiftuitableviewrealm

解决方案


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

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

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)

推荐阅读