Reputation: 61
I'm replicating the sample Food Tracker app from apple and have an issue where the items from my TableView in Edit mode don't show the left hand delete icon (the round red one). If I swipe left I get a delete button on the right. I've downloaded the Food Tracker code and it works.
The difference I can see is that the sample app has implemented a UITableViewController, whereas I have a UITableView within a standard UIViewController. I'm not sure why this doesn't work.
There are some similar questions but they are older versions of Swift / Ios, so I'm not sure they are still relevant.
Here is the link to the sample app https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/index.html#//apple_ref/doc/uid/TP40015214-CH2-SW1
Here are the funcs I recently added that should make it work
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
//delete the row from the dataSource
dataSource.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
else if editingStyle == .insert {
//create a new instance and insert the row
}
}
And I added this to the ViewDidLoad() to get the Edit button in the Nav bar
navigationItem.leftBarButtonItem = editButtonItem
Here's what the Food Tracker example looks like;
and mine is missing the left hand button. The only difference I can see is that I'm using a TableView inside a ViewController.
Thanks
Nick
Upvotes: 0
Views: 2622
Reputation: 701
No need to check the title of the barButtonItem as tapping it already toggles its state and passes the correct state in editing param.
Also, when overriding, you need to invoke super's implementation as absence would always show the delete indicator.
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: true)
tableView.setEditing(editing, animated: true)
}
Upvotes: 2
Reputation: 61
I think I solved this. Effectively there's a fair bit of 'magic' that a UITableViewController is doing. To recreate this in a normal UIViewController with a TableView you have to override the SetEditing function and based on the title of the button put it in edit mode.
override func setEditing(_ editing: Bool, animated: Bool) {
let status = navigationItem.leftBarButtonItem?.title
if status == "Edit" {
tableView.isEditing = true
navigationItem.leftBarButtonItem?.title = "Done"
}
else {
tableView.isEditing = false
navigationItem.leftBarButtonItem?.title = "Edit"
}
}
Upvotes: 1