【问题标题】:SwipeCellKit: Why removing an item from list, doesn't update the UITableview?SwipeCellKit:为什么从列表中删除一个项目,不更新 UITableview?
【发布时间】:2021-02-14 11:23:32
【问题描述】:

当我使用 SwipeTableViewCell 从列表中删除项目时,表格视图不会更新。 滑动有效,我也可以点击单元格后面的删除按钮,但是一旦点击它,它只会隐藏删除按钮,但不会更新 tableview。 这就是我的代码的样子:


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return carList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell_id", for: indexPath) as! CarCell

        (cell as SwipeTableViewCell).delegate = self
        
        let car = carList[indexPath.row]
        cell.configure(with: car)

        return cell
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        
        guard orientation == .right else { return nil }
        
        let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
            
            self.carList.remove(at: indexPath.row)
        }
        deleteAction.hidesWhenSelected = true

        return [deleteAction]
    }


当我调用 tableview 的 reloadData 时它可以工作,但我猜这不是正确的方式。以下 sn-p 代码有效:


    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        
        guard orientation == .right else { return nil }
        
        let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
            
            self.carList.remove(at: indexPath.row)
            
            self.tableView.reloadData() // <-- this works! But without animation
        }
        deleteAction.hidesWhenSelected = true

        return [deleteAction]
    }


【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    您必须添加代码来更新视图,而不是重新加载整个表格视图,只需 删除

    let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
            
        self.carList.remove(at: indexPath.row)
        self.tableView.deleteRows(at: [indexPath], with: .fade)
    }
    

    【讨论】:

    • 我认为 SwipeCellKit 有一种方法可以自动触发 tableview 更新数据。在第 141 行的 SwipeCellKit 源代码中,没有 self.tableView.deleteRows(at: [indexPath], with: .fade),但它的行为相同。这怎么可能?
    • 我不知道SwipeCellKit,但正如你所写的那样,它与reloadData 一起工作,我写了我的答案。我什至看不到SwipeCellKit 的好处。
    • SwipeCellKit 在现有的自定义 UITableViewCell 上添加了滑动功能。自定义后,您将无法再使用默认的滑动功能,因此 SwipeCellKit。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2019-01-26
    • 2017-09-06
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多