Reputation: 37
I received great advice from Stack Overflow a few days ago. It was to prevent the last cell from moving within the UITableView. It uses the following code.
func tableView (_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if indexPath.row <myTableviewArray.count {
return true
}
return false
}
And the code I used to move the cells is:
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if destinationIndexPath.row != menuDic.count {
let movedObject = menuDic[sourceIndexPath.row]
menuDic.remove(at: sourceIndexPath.row)
menuDic.insert(movedObject, at: destinationIndexPath.row)
}
}
But there was an unexpected problem. Another cell was moving underneath the last cell! Cells except the last must not move below the last cell. The last cell should always be last.
I used the following two codes, but all failed.
func tableView (_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if proposedDestinationIndexPath.row == myTableviewArray.count - 1 {
return IndexPath (row: myTableviewArray.count - 1, section: 0)
}
return proposedDestinationIndexPath
}
func tableView (_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if destinationIndexPath.row! = myTableviewArray.count {
let movedObject = myTableviewArray [sourceIndexPath.row]
myTableviewArray.remove (at: sourceIndexPath.row)
menuDic.insert (movedObject, at: destinationIndexPath.row)
}
}
Using these two codes, the cell will still move underneath the last cell. Stack Overflow. Thank you all the time! :)
Upvotes: 1
Views: 540
Reputation: 4008
indexPath.row
starts at zero. if myTableviewArray
is your data source.
indexPath.row <myTableviewArray.count
, this will be always true.
try using :
func tableView (_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if indexPath.row < myTableviewArray.count - 1 {
return true
}
return false
}
Upvotes: 2