ios - 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)
}
解决方案
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)
推荐阅读
- python - 使用python PIL批量平铺图像,按文件夹重复填充背景图像
- reactjs - 以反应钩子形式发布请求未获取用户输入
- c++ - 您如何检查/匹配从“句子”的单词编号“wordNum”开始的“字符串”到“句子”
- mysql - 如何从 MySQL 中的字符串中删除某些字符?
- python - 仅在一个过滤器之后的 Tweepy 流过滤器
- javascript - JavaScript中递归问题的麻烦。根据对象数组创建对象树
- reactjs - menuPortalTarget 在 AsyncSelect 中无法正常工作
- c++ - ncurses中的“红心❤️”Unicode字符
- go - net/http 和 ant 每次运行都会给我不同的结果
- powershell - 在 Powershell 中使用 Invoke-SSHCommand 传递变量