How can I add/remove cells in a table view more elegantly?

前端 未结 3 415
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 09:34

I think this is probably an X Y problem, so I\'ll give some background info first.

I am building an app that can show a \"form\". The user can fill in the form with

3条回答
  •  太阳男子
    2020-12-20 10:05

    I found a solution!

    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!

提交回复
热议问题