ios - 根据 Swift 3 中 UITableView 中的单元格选择删除文件

标签 ios swift uitableview

我想在 Swift 中制作一个表格,它将显示一个文件的名称,并允许用户通过单击一个单元格将其从 documentDirectory 中删除。

我是 Swift 的新手,遇到了一个无用的错误。这就是我在做什么。首先,我为这些 URL 创建了一个名为 theurls 的变量,并将其定义为 documentDirectory 的所有内容。

class DownloadTableViewController: UITableViewController {

var theurls = [URL]()


override func viewDidLoad() {
    super.viewDidLoad()

    // Get the document directory url
    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    do {
        // Get the directory contents urls (including subfolders urls)
        let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
        // print(directoryContents)
        theurls = directoryContents

    } catch {
        print(error.localizedDescription)
    }

使用 this answer ,我尝试让每个单元格对应于 theurls 中的一个 URL。我应该注意,这还没有文本标签,但我想我可以稍后添加。

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let url = thedownloads[indexPath.row]
        print(url)

        try FileManager.default.removeItem(at: theurls[indexPath.row])


    }

Throws 不处理从这里抛出的错误。我想将每个单元格设置为文本标签,然后在单击该单元格时删除该项目。有一个更好的方法吗?

最佳答案

错误处理代码使用 do-catch block :

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let url = thedownloads[indexPath.row]
    print(url)

    do {
        try FileManager.default.removeItem(at: theurls[indexPath.row])
    } catch {
        print(error)
    }
}

关于ios - 根据 Swift 3 中 UITableView 中的单元格选择删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48801752/

相关文章:

ios - 如何使用 swift 创建一个闹钟应用程序?

iphone - 如何使 UITableView 中的第一列不在 iPhone Objective-C 中水平滚动?

ios - 使用 AutoLayout 将 UIView 隐藏在单元格内时,UITableViewCell 高度不合适

iOS 应用商店拒绝 : Privacy Policy URL

ios - Uiwebview 使用 Swift 隐藏/显示 UInavigationbar

ios - 在没有 xib 文件的情况下更改我的标签栏颜色

iphone - 什么时候在模态视图 Controller 上设置父/呈现 View Controller ?

ios - 向下滚动点击按钮继续下一个屏幕后如何验证 CustomCell 中的 UITextField - Swift 2.3

swift - 当@State 变量以高频率刷新 View 时,导航栏/工具栏按钮工作不可靠

objective-c - 在 UIScrollView 中滚动 UITableView