我在表格视图中使用了滑动操作。我想在滑动操作完成后在行中添加和删除小图标。我使用异步线程来执行此操作,但是并没有达到我想要的平滑结果。下面提供了我的代码,将对您有所帮助。
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
}
答案 0 :(得分:1)
最后我明白了。我只是使用了来自tableview委托的以下函数。
func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
print("did end editing")
guard let indexPath = indexPath else {return}
tableView.reloadRows(at: [indexPath], with: .none)
}
答案 1 :(得分:0)
DispatchQueue.main.async
{
self.tableView.reloadData()
}
应该足够。
在您的代码中,您强制应用程序在特定时间执行。如果您的数据是动态的,例如远程图像,它们可能会使主循环延迟0.4秒以上,从而导致更新和移动更加不稳定。
答案 2 :(得分:0)
您需要集成UITableView删除行,这将提供很好的动画效果,而不是笨拙的重载视图更新。
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)