Rapsefar Rapsefar - 1 month ago 14
iOS Question

TableView section header moves when a row is edited

I'm building an iOS app with a tableView, it's using a Realm database for the datamodel. When I try to delete a row by dragging the cell towards left, the section header follows the dragging movement to the left. When delete is pressed, the cell is deleted and the section header moves back into the right place.

Any clues to why the section header is moving with the cell?

The header cell is defined in the storyboard as a dynamic prototype cell, and the row cells are defined in a seperate xib and registered in the tableview. The section cell has the "Indent While Editing"-option unchecked in the storyboard.

The "Weekly report" is in the section header.

Before and after dragging to edit

Here is the code I've implemented to enable editing:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}


func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

if editingStyle == .delete {
try! realm.write {
let reportToDelete = reportList[indexPath.row]
realm.delete(reportToDelete)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}


I've tried both on the device and two different simulators, and with cleanin the build folder.

EDIT

The header is loaded from the storyboard, where it has a reuseable identifier: "WeeklyReportHeader", and the UIView in return by the tableView's delegate.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableCell(withIdentifier: "WeeklyReportHeader")! as UIView
}

Answer

I think this has something to do with using a cell as the header, probably some issue to do with cell reuse.

To fix this, rather than using the cell itself (and casting it as a UIView for the header), use it's contentView property, which is a UIView anyways.

Eg

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    return tableView.dequeueReusableCell(withIdentifier: "WeeklyReportHeader")!.contentView
}