2017-07-03 26 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)** –