ios - 从正在删除的 UITableViewCell 中获取标题

标签 ios swift uitableview nsuserdefaults

我希望能够获取正在使用 commit editStyle: UITableViewCellEditingStyle 删除的 UITableViewCell 的标题。这是您需要了解的我的代码。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell : FavoritesTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Favorites Cell") as! FavoritesTableViewCell
        if(cell == nil)
        {
            cell = Bundle.main.loadNibNamed("Favorites Cell", owner: self, options: nil)?[0] as! FavoritesTableViewCell;
        }

        cell.songTitle.text=favoriteSongs[indexPath.row].title

        return cell as FavoritesTableViewCell
    }

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {

            // remove the item from the data model
            favoriteSongs.remove(at: indexPath.row)

            // delete the table view row
            tableView.deleteRows(at: [indexPath], with: .fade)
            let propertylistSongs = favoriteSongs.map{ $0.propertyListRepresentation }
            UserDefaults.standard.set(propertylistSongs, forKey: "favoriteSongs")


        } else if editingStyle == .insert {

        }
    }

我想这样做的原因是我可以为 UserDefaults 创建一个 key 。我当时在想:

    var cell : FavoritesTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Favorites Cell") as! FavoritesTableViewCell
    UserDefaults.standard.set(false, forKey: "liked\(String(describing: cell.songTitle.text))")

但是,我想这不起作用,因为每当引用 UserDefaults bool 时,Key 都不起作用。因此,我需要从正在删除的 UITableViewCell 中获取 SongTitle.text。有什么想法吗?

最佳答案

简单的解决方案就在这里

我从您的代码中发现,首先您要从数组中删除该对象,但您可以从该索引中获取该歌曲的标题,而不是删除它

这里是详细说明

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == .delete {

            print(favoriteSongs[indexPath.row]) //Here is your title for the deleted song

            // remove the item from the data model
            favoriteSongs.remove(at: indexPath.row)

            // delete the table view row
            tableView.deleteRows(at: [indexPath], with: .fade)

        } else if editingStyle == .insert {

        }
    }

关于ios - 从正在删除的 UITableViewCell 中获取标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44891406/

相关文章:

ios - iOS 被拒绝后有没有办法请求许可

swift - 观察 Firebase 的特定数据集

ios - 将字典键与数组进行比较以提取匹配和不匹配的数据

ios - 多选快速搜索

ios - ITSAppUsesNonExemptEncryption 不再起作用

ios - 如何修改我的应用程序概念以通过包含原生 iOS 特性和功能来提供更强大的用户体验?

ios - 触摸 searchBar 时未调用 updateSearchResults 函数

iphone - 动态添加和删除 UITableViewCells 到 UITableView

ios - 从不响应 iPad 的其他 ViewController 调用 didSelectRowAtIndexPath

ios - 是否可以在后台模式下运行 Quickblox SDK?