首页 > 解决方案 > Deleted tableviewcell gets replaced by last cell

问题描述

I've got a problem with my tableView that is filled with realm objects. When I delete a cell the last cell of the tableView is jumping into the place of the removed cell. Anybody knows what could be the reason for this behavior?

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == UITableViewCellEditingStyle.delete{

        self.updateModel(at: indexPath)
        self.loadTimes()
    }
}

func loadTimes(){

    results = realm.objects(Times.self)
    tableView.reloadData()
}

 func updateModel(at indexpath: IndexPath) {
    if let itemForDeletion = results?[indexpath.row] {
        do{
            try self.realm.write {
                self.realm.delete(itemForDeletion)
            }
        } catch {
            print("Error saving context \(error)")
        }
    }
}

标签: swiftuitableviewrealmcell

解决方案


Realm 仅在对Results查询进行排序时才保证顺序一致。尝试添加呼叫sorted

results = realm.objects(Times.self)

变成

results = realm.objects(Times.self).sorted(byKeyPath: "time")

推荐阅读