如何在带有自定义表格视图单元格的表格视图中滑动删除?

问题描述

目前,我有一个屏幕显示带有自定义单元格的 TableView,每个单元格都有一个文本字段和一个按钮。我将文本字段的数据输入存储到 taskName dict 和按钮的标题选择(从弹出屏幕)到 taskTime dict

但是,我的问题是当我在 TableView 中滑动以删除一行时,它会删除存储在该行中的数据,但不会删除该行本身(如下面的动画所示)。

这是我的代码:

带有 TableView + 自定义单元格的屏幕

class TaskListViewController: UIViewController {
    
    @IBOutlet weak var taskList: SelfSizedTableView!
    
    var taskCount: Int = 1
    var taskName = [Int:String]()
    var taskTime = [Int:String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set initial taskTime value
        taskTime[0] = "Set time"

        taskList.delegate = self
        taskList.dataSource = self
    }
}

extension TaskListViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return taskCount
    }
    
    // Return custom cell + data to insert in table view
    func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell",for: indexPath) as! TaskCell
        
        cell.delegate = self
        
        // Configure nameField and timeButton in taskCell
        cell.nameField.text = taskName[indexPath.row]
        cell.timeButton.setTitle(taskTime[indexPath.row],for: .normal)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView,commit editingStyle: UITableViewCell.EditingStyle,forRowAt indexPath: IndexPath) {

        // Update # of rows in taskList
        taskCount -= 1

        // Row that is deleted
        let deleteRowIndex = indexPath.row
        print(deleteRowIndex)

        // Remove taskName + taskTime from dictionary
        taskName[deleteRowIndex] = nil
        taskTime[deleteRowIndex] = nil

        // Delete row from table view
        let indexPaths = [indexPath]
        taskList.deleteRows(at: indexPaths,with: .fade)
        
        // Reload table view with new data
        taskList.reloadData()
    }
}

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)