randomizedLife
randomizedLife

Reputation: 37

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.

Upvotes: 1

Views: 1158

Answers (2)

Ahmad F
Ahmad F

Reputation: 31645

At this point, you need to tell the table view that the last row should not be moved. You could achieve this by implementing tableView(_:canMoveRowAt:) data source method:

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    // '??' means the last row...
    return indexPath.row == ?? ? false : true
}

assuming that you are already know the number of rows, you should check the last one.


Furthermore: for your case it might be a good idea to the button as tableFooterView instead of row, therefore there is no need to implement the above method.

Upvotes: 2

holex
holex

Reputation: 24041

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.

Upvotes: 3

Related Questions