4

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

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

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
}
4

3 回答 3

3

最后我想通了。我只是从 tableview 委托中使用了以下函数。

func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
    print("did end editing")
    guard let indexPath = indexPath else {return}
    tableView.reloadRows(at: [indexPath], with: .none)
}
于 2019-01-18T08:35:48.510 回答
1

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

tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
于 2019-01-17T19:57:18.117 回答
0
DispatchQueue.main.async
{
    self.tableView.reloadData()
}

应该够了。

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

于 2019-01-17T18:25:07.727 回答