[英]TableView row height shrinks when I am trying to reorder row using tableView(moveRowAt:)
[英]moveRowAt Reorder TableView with Realm
我有 Realm model:
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
}
我應該向 function 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 中的行重新排序時,通過將其插入新的 position 並將其從舊的刪除(首先完成取決於 object 移動的方向)來反映列表中的更改。 您可以使用 .insert 和 .remove 手動完成
itemList.remove(at: 5) //remove the shoppingItem object at index 5
itemList.insert(shoppingItem, at: 1) //insert the object at index 1
或使用 super easy.move 將 object 從一個索引移動到另一個索引。
itemList.move(from: 5, to: 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.