Search code examples
iosswiftuitableviewmove

Disable move last row using Swift and UITableview


I am an iOS developer and I am currently developing an app using UITableView. The last row of the UITableView contains a button.

But there was a problem here. I put the move (moveRowAt) function in the row, and I can move to the last row! The last row should not be moved. It should always be located in the last row. The last row must have 'moveRowAt' disabled.

I looked up a lot of information, including Stack Overflow, but I did not get any clues.


Solution

  • maybe I could do a bit more than a plain comment by making a sample implementation of making the last row immovable in every section you may have:

    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return self.tableView(tableView, numberOfRowsInSection: indexPath.section) - 1 != indexPath.row
    }
    

    NOTE: if you have your datasource and the number of data accessible anywhere else, it would be more desirable to get the number of rows (in section) from there not by calling the delegate method (as I did here) – however, logically there is nothing wrong with any of the concepts; by the way: here is the class-ref docs of tableView(_:canMoveRowAt:), of you want to know more about it.