1

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! :)

1 Answers1

2

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
    }
dengApro
  • 3,848
  • 2
  • 27
  • 41
  • 1
    Thanks for your reply :) My datasource is always MyArray + 1. Because my data source always append +1(It's Button). I tried this one, but it's fail again – randomizedLife Oct 31 '18 at 10:07
  • 1
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let movedObject = menuDic[sourceIndexPath.row] menuDic.remove(at: sourceIndexPath.row) if destinationIndexPath.row == menuDic.count { menuDic.insert(movedObject, at: sourceIndexPath.row) } menuDic.insert(movedObject, at: destinationIndexPath.row) } – randomizedLife Oct 31 '18 at 10:08