且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更优雅地在表格视图中添加/删除单元格?

更新时间:2022-02-20 23:01:52

我找到了解决方案!

我基本上保留了一个单元格数组的数组,供表格视图显示:

I basically keep an array of an array of cells for the table view to display:

var cells: [[UITableViewCell]] = [[], [], []] // I have 3 sections, so 3 empty arrays

然后我添加了这些数据源方法:

And then I added these data source methods:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return cells.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cells[section].count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    return cells[indexPath.section][indexPath.row]
}

现在,我可以轻松地添加和删除单元格:

Now, I can add and remove cells super easily:

func addCellToSection(section: Int, index: Int, cell: UITableViewCell) {
    cells[section].insert(cell, atIndex: index)
    tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: section)], withRowAnimation: .Left)
}

func removeCellFromSection(section: Int, index: Int) {
    cells[section].removeAtIndex(index)
    tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: section)], withRowAnimation: .Left)
}

只有两行,我可以用动画添加/删除单元格!

With just two lines, I can add/remove cells with animation!