2017-07-03 27 views
0

我希望能够获取commit editingStyle: UITableViewCellEditingStyle正在删除的UITableViewCell的标题。这是我需要知道的代码。从正在删除的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创建一个键。我的想法是这样的:

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

但是,我想,没有工作,因为每当UserDefaults布尔引用的键不起作用。所以,我需要从正在删除的UITableViewCell中获取songTitle.text。有任何想法吗?

+0

你只是想要当前删除的歌曲标题,或者你想要所有的东西已经删除? –

+0

由于您在“commit editingStyle:UITableViewCellEditingStyle”方法中删除了indexpath,因此如果您从编辑样式== .delete {...} –

回答

0

简单的解决办法是在这里

我从你的代码中发现什么是你首先从数组删除对象,但在地方删除它,你可以从指数

拿到冠军的那首歌这里详细说明

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 { 

     } 
    } 
+0

实际删除 中的数据源之前可以获得标题唯一的问题是,我正在使用一个结构体,所以'favoriteSongs [indexPath.row]'变成'favoriteSongs [indexPath.row]'.title我得到一个错误**线程1 EXC_BAD_INSTRUCTION(code = EXC_1386_INOP,subcode =为0x0)** –