我想在 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/