簡體   English   中英

在UITableview中刪除一行后,在底部插入新行

[英]Insert new row at the bottom upon deleting a row in UITableview

我有一個需要始終顯示三行的tableview的要求。

當用戶滑動刪除行時,我需要在底部添加新行。

在這種情況下,必須保留將行向左移動以進行刪除的滑動動畫。 我的意思是刪除動畫不應該受到影響。 這可能嗎?

首先,您的dataSource必須始終為numberOfRows(in:)方法返回3。 然后,您可以通過以下方式提交更改:

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)
    }
}

不要忘記相應地更新其余的dataSource ,因為單元可能會被重用。 需要調用performBatchUpdates 之前添加代碼。 像這樣:

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

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

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

    // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM