【问题标题】:Swift - Delete cell from UITableViewSwift - 从 UITableView 中删除单元格
【发布时间】:2017-05-24 13:58:15
【问题描述】:

我正在按照此代码从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 中删除。那太棒了。但是当我关闭我的应用程序并再次重新启动我的应用程序时,会出现已删除的单元格。 音频文件存储在文档目录中。

【问题讨论】:

  • 此代码是数组中的元素,但您还需要删除文件或用于在应用启动时将数据加载到数组的任何内容
  • 那么您还需要从文档目录中删除该文件。
  • 您还需要从文档目录中删除此文件。因为您只是从数组中删除元素,而不是删除实际文件。一旦再次填充数据,它也会再次加载整个数据。跨度>

标签: ios swift uitableview nsdocumentdirectory


【解决方案1】:
objects.remove(at: 0)
let indexPath = IndexPath(item: 0, section: 0)
tableView.deleteRows(at: [indexPath], with: .fade)

【讨论】:

  • 欢迎来到 Stack Overflow,感谢您提供答案。您能否编辑您的答案以包括对您的代码的解释?这将有助于未来的读者更好地理解正在发生的事情,尤其是那些不熟悉该语言并努力理解这些概念的社区成员。当社区已经验证了已接受的答案时,这一点尤其重要。在什么条件下你的方法可能更受欢迎?您是否在利用新功能?
【解决方案2】:
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)")
       }
}

【讨论】:

    【解决方案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()
        }
    }
    

    【讨论】:

    • @pigeon_39 欢迎朋友 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多