如何在滑动操作后更新 tableview 行?

How to update the tableview row after swipe action?

我在我的表格视图中使用滑动操作。我想在完成滑动操作后添加和删除行上的小图标。

我使用异步线程来执行此操作,但是它没有给出我想要的平滑结果。我的代码在下面给出了任何帮助。

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let groceryAction = groceryToggleAction(forRowAtIndexPath: indexPath)
    let config = UISwipeActionsConfiguration(actions: [groceryAction])
    return config
}

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let consumeAction = consumeToggleAction(forRowAtIndexPath: indexPath)
    let config = UISwipeActionsConfiguration(actions: [consumeAction])
    return config
}

// MARK: Custom Methods
func groceryToggleAction(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
    let food = foods[indexPath.item]
    let action = UIContextualAction(style: .normal, title: "actionTitle") { (action, view, completionHandler) in

        let food = self.foods[indexPath.item]

        food.isAddedToGrocery = !food.isAddedToGrocery
        self.persistenceManager.saveContext()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
            self.homeTableView.reloadRows(at: [indexPath], with: .none)
        }
        completionHandler(true)
    }
    action.image = #imageLiteral(resourceName: "shoppingCart") // İyi bir liste ikonu bul...
    action.backgroundColor = food.isAddedToGrocery ? UIColor.Palette.alizarin : UIColor.Palette.turquoise
    action.title = food.isAddedToGrocery ? "Remove" : "Add"
    return action
}

func consumeToggleAction(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
    let food = foods[indexPath.item]

    let action = UIContextualAction(style: .normal, title: "actionTitle") { (action, view, completionHandler) in

        food.isConsumed = !food.isConsumed
        self.persistenceManager.saveContext()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
            self.homeTableView.reloadRows(at: [indexPath], with: .none)
        }
        completionHandler(true)

    }
    action.image = #imageLiteral(resourceName: "pacman")
    action.title = food.isConsumed ? "Remove": "Consumed!"
    action.backgroundColor = food.isConsumed ? UIColor.Palette.alizarin : UIColor.Palette.turquoise
    return action
}
DispatchQueue.main.async
{
    self.tableView.reloadData()
}

应该够了。

在您的代码中,您强制应用程序在特定时间执行。如果您的数据是动态的,例如远程图像,它们可能会使主循环延迟超过 0.4 秒,从而导致更不稳定的更新和移动。

您需要集成 UITableView 删除行,这将提供漂亮的动画,而不是笨重的重新加载视图更新。

tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

我终于明白了。我只是使用了来自 tableview delegate 的以下函数。

func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    print("did end editing")
    guard let indexPath = indexPath else {return}
    tableView.reloadRows(at: [indexPath], with: .none)
}