ios - 当数组中存在数据时,无法将 UITableViewRowAction 的标题从收藏夹更改为删除
问题描述
在向左滑动表格视图单元格时,会出现一个带有标题收藏夹的按钮,该按钮将当前行标题保存为默认值,第二次向左滑动相同的按钮,收藏夹按钮会从默认数组中删除当前单元格标题。第二次向左滑动时,我希望标题为“删除不喜欢”。请帮忙。
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
var titleFavoriteButton = "Favorite"
let favorite = UITableViewRowAction(style: .normal, title:
"Favorite") { [unowned self] (action, indexPath) in
let defaults = UserDefaults.standard
var favorites = defaults.array(forKey: "favorites") as? [String] ?? []
if let datastring = itemList[indexPath.row] as? String {
if favorites.contains(datastring) {
favorite.title = "Remove"
favorites.remove(at: favorites.index(of: datastring)!)
} else {
favorites.append(datastring)
}
defaults.set(favorites, forKey: "favorites")
}
print(favorites)
}
return [favorite]
}
解决方案
您必须在创建操作之前检查收藏夹是否存在
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let defaults = UserDefaults.standard
var favorites = defaults.array(forKey: "favorites") as? [String] ?? []
let item = itemList[indexPath.row]
let favoriteIndex = favorites.firstIndex(of: item)
let actionTitle = favoriteIndex == nil ? "Favorite" : "Remove"
let favorite = UITableViewRowAction(style: .normal, title: actionTitle) { (action, indexPath) in
if let index = favoriteIndex {
favorites.remove(at: index)
} else {
favorites.append(item)
}
defaults.set(favorites, forKey: "favorites")
print(favorites)
}
return [favorite]
}
推荐阅读
- sql - ' 在过程/函数上
- python - 有没有一种在 keras 中应用径向平均值的有效方法?
- unit-testing - 在单元测试中将预期结果基于实际结果是不好的做法吗?
- python-2.7 - 错误:后视需要固定宽度的图案 Spacy
- cassandra - 是否可以在具有多个数据中心的 cassandra 集群中拥有“本地”键空间
- java - 如何按java 8中列表对象的多个参数分组并删除重复行?
- html - 更改动画响应按钮的颜色
- python-3.x - 如何制作仅在出现“返回”按钮时才停止的循环?
- youtube-data-api - 通过 google-api-php-client 来自 Youtube API 的 accessNotConfigured 错误 (403)
- python - 求解带约束的线性方程