To prevent a row from being editable, we have to implement two methods: tableView(_:canEditRowAt:) of UITableViewDataSource protocol and tableView(_:targetIndexPathForMoveFromRowAt:toProposedIndexPath) of UITableViewDelegate protocol.
1. Disabling editable style
Implement the method tableView(_:canEditRowAt:) as following:
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if isLastRowOfSection(tableView, indexPath) {
return false
}
return true
}
When the method tableView(_:canEditRowAt:) returns false, the deletion control (a minus sign in a red circle at the left of the cell) and moving control (gray horizontal bars at the right of the cell) does not show up for that row/cell (the "No More Items" row in this example). Then, the users can't drag that row to move it up or down anymore.
However, they can still move another editable row to the position of this non-editable row and then this non-editable row will automatically move to the position of the editable row. This is the default behavior of the table view control. Please see the image below.
2. Preventing an editable row from moving to the position of non-editable row
Implement the method tableView(_:targetIndexPathForMoveFromRowAt:toProposedIndexPath)
as following:
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if isLastRowOfSection(tableView, proposedDestinationIndexPath) {
return sourceIndexPath
}
return proposedDestinationIndexPath
}
When the users drag the editable row over the non-editable row (the last row in this example), the non-editable row does not move. It stays where it is. And the editable row moves back to its original position when the users release it.
No comments:
Post a Comment