2017-01-10 101 views
3

刪除單元格我從UITableView斯威夫特 - 從UITableView中

var recordedAudioFilesURLArray = [URL]() 
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 
     return true 
    } 

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      recordedAudioFilesURLArray.remove(at: indexPath.row) 
      self.tableView.reloadData() 
     } 
    } 

當我往左滑動可切換到特定小區的下面這段代碼刪除數據時,細胞從UITableView刪除。那很棒。但是,當我關閉我的應用程序,並再次啓動我的應用程序,刪除單元格出現。 音頻文件存儲在文檔目錄中。

+1

這段代碼從數組的元素,但你還需要刪除的文件或任何用於加載數據*成*數組當你的應用程序啓動 – Paulw11

+1

然後你還需要刪除該文件文檔目錄。 –

+1

您還需要從文檔目錄中刪除此文件。因爲您只是從數組中刪除元素,但不刪除實際的文件。一旦您再次填充數據,它也會再次加載整個數據。 –

回答

3

使用該URL數組從DocumentDirectory中刪除該文件,然後從Array中刪除該對象。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 

     //First remove file from DocumentDirectory 
     try? FileManager.default.removeItem(at: recordedAudioFilesURLArray[indexPath.row]) 

     //Remove object from array 
     recordedAudioFilesURLArray.remove(at: indexPath.row) 

     //Reload tableView 
     self.tableView.reloadData() 
    } 
} 
+0

謝謝...它的作品:) –

+0

@ pigeon_39歡迎隊友:) –

0
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
    if editingStyle == .delete { 
     recordedAudioFilesURLArray.remove(at: indexPath.row) 
     self. clearAllFilesFromTempDirectory(indexPath.row); 
     self.tableView.reloadData() 
    } 
} 

func clearAllFilesFromTempDirectory()->fullPath 
{ 

     if fileManager.removeItemAtPath(fullPath, error: error) == false 
     { 
      println("delete successfully") 
     } 


    else 
     { 
     println("Could not retrieve directory: \(error)") 
     } 
}