简体   繁体   中英

Insert new row at the bottom upon deleting a row in UITableview

I have a requirement where I need to show a tableview with three rows always.

When user swipes to delete a row, I need to add a new row at the bottom.

While this happens, the swipe animation which moves the row to the left to delete has to be retained. I mean delete animation should not be affected. Is this possible?

First, your dataSource must return always 3 for your numberOfRows(in:) method. Then you can commit changes this way:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        tableView.performBatchUpdates({

            // Delete the swiped row
            tableView.deleteRows(at: [indexPath], with: .left)
            // Get the last row index (numberOfRows-1)
            let lastRowIndex = tableView.numberOfRows(inSection: indexPath.section)-1
            // Insert a new row at the end
            tableView.insertRows(at: [IndexPath(row: lastRowIndex, section: 0)], with: .top)

        }, completion: nil)
    }
}

Don't forget to update the rest of your dataSource accordingly, because cells may be reused. The code need to be added before call performBatchUpdates . Something like that:

var cellsText = ["A","B","C"]

// Inside your tableView(:commit:forRowAt) method:

if editingStyle == .delete {
    cellsText.remove(at: indexPath.row)
    cellsText.append("D")

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM