首页 > 解决方案 > 当数组中存在数据时,无法将 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]
 }

这是工作输出 这是工作输出

标签: iosswift

解决方案


您必须在创建操作之前检查收藏夹是否存在

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

推荐阅读