在我使用Swift 3的应用中,我希望允许用户在UITableView
中滑动一行以将其从表中删除。 This guide使它看起来非常简单,我实现时没有XCode错误。
如上一种方法所示,用户应该能够滑动,并且将删除所选行。在模拟器中运行后,似乎没有任何事情发生,并且没有控制台输出。
我是Swift的新手 - 有更好的方法来解决这个问题吗?请注意,thedownloads
是包含存储在每个表格单元格中的数组的数据源。我已将该代码作为FYI包含在内。
var thedownloads = [String]()
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: [])
// if you want to filter the directory contents you can do like this:
let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
//print("mp3 urls:",mp3Files)
let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
//print("mp3 list:", mp3FileNames)
thedownloads = mp3FileNames
} catch {
print(error.localizedDescription)
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "showcell", for: indexPath)
cell.textLabel?.text = thedownloads[indexPath.row]
return cell
}
// this is where I try to run the delete animation
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
thedownloads.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath as IndexPath], with: UITableViewRowAnimation.automatic)
}
}
答案 0 :(得分:2)
我能够复制你的错误,这取决于这些:
1:你没有覆盖commitEditingStyle
2:您使用commitEditingStyle
将commit EditingStyle
功能更新为此功能,它将对您有用:
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
thedownloads.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}