PhilHarmonie
PhilHarmonie

Reputation: 435

Swift: Reorder Table Rows programmatically

I have a TableViewController with rows that hold tasks. If a task has an attribute task.done = 1 I want to move it at the bottom from the table. I can't provide any code, because I have no doubt how to do this.

My idea was in tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) using following code:

let element = tasks.remove(at: indexPath.row)
tasks.insert(element, at: tasks.count)

The issue is, that this needs to be done after the table is loaded, because if the first row is done = 1 for example, it will be moved to to bottom and will be processed at the end again.

Upvotes: 1

Views: 2932

Answers (2)

Jaya Mayu
Jaya Mayu

Reputation: 17257

You can programmatically remove a row from UITableView and insert a row programmatically. Before doing the operations on the UITableView, make sure to remove/add a specific item to the data source array. Otherwise, it'll just crash.

If you want to simply move the rows, you can use the code below. You need to do it in the place where the array which holds the data source is updated.

tableView.moveRow(at: oldIndexPath, to: newIndexPath)

If you want to do delete and insert new objects into the array, you may try the method as shown below.

let element = tasks.remove(at: indexPath.row)
tableView.deleteRows(at: indexPath, with: .automatic)

tasks.insert(element, at: tasks.count)
tableView.insertRows(at: [IndexPath(row: tasks.count, section: 0)], with: .automatic)

Upvotes: 3

user1376400
user1376400

Reputation: 624

Wrap your code in a beginUpdates-endUpdates block.Use func moveRow(at indexPath: IndexPath, to newIndexPath: IndexPath)

For example: Not tested

self.tableView.beginUpdates()
let element = tasks.remove(at: indexPath.row)
let  movingRowIndex = indexPath.row
tasks.insert(element, at: tasks.count)
let indexPath = NSIndexPath(forRow: movingRowIndex, inSection: 0)
var lastIndexPath = NSIndexPath(forRow:tasks.count, inSection: 0)
self.tableView.moveRow(at indexPath: IndexPath, to newIndexPath: lastIndexPath)
self.tableView.endUpdates()

Upvotes: 0

Related Questions