tableView(canEditRowAt) no longer working with tableViewDiffableDataSource - uitableview

I created a fairly simple tableView for selecting a category for an item model. Everything was working fine yesterday. Today I have been trying to switch the tableView data source over to a UITableViewDiffableDataSource as I want to wrap my head around the API. I have the entire tableView back up and running EXCEPT I can no longer edit my rows!
the setEditing logic works as the newCategoryButton is disabled when I tap the edit button in the navigation bar and is enabled when I tap it again. However, I am never able to swipe to delete and the delete icons do not show up next to my rows in editing mode.
I tried removing setEditing, emptying out commit editingStyle and simply setting canEditRow to return true and still nothing.
Any help would be greatly appreciate. Thank!
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
let section = dataSource.snapshot().sectionIdentifiers[indexPath.section]
if section == .noneSelected {
return false
} else {
return true
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: true)
if editing == true {
newCategoryButton.isEnabled = false
} else {
newCategoryButton.isEnabled = true
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
categories.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedCategory = categories.remove(at: sourceIndexPath.row)
categories.insert(movedCategory, at: destinationIndexPath.row)
}
screenShot after edit button is tapped

The trouble is that canEditRowAt is a data source method. You (the view controller) are now not the data source; the diffable data source is. You need to implement this method inside the diffable data source. That's typically done by subclassing the diffable data source class, so that you can override this method. Otherwise, the diffable data source just returns its default value — which is false, which is why you currently can't edit any rows.

Related

UITableView insert row decoration

I am trying enable editing of my UITableView by providing an Edit button on the nav bar.
The intention is to allow the user to insert new items and delete existing items.
When clicking the Edit button iOS shows the "Delete" decoration (deleting works fine), but doesnt show "Insert"
I have added navigationItem.rightBarButtonItem = editButtonItem to my UIViewControllers viewDidLoad and have added the following methods to my UITableViewDataSource delegate:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
AppDelegate.persistenceContext.delete(self.fetchedResultsController.object(at: indexPath))
AppDelegate.saveContext()
} else if editingStyle == .insert {
let current = self.fetchedResultsController.object(at: indexPath)
// do rest of insertion logic
}
}
What am I missing something?
Oh and out of interest, if this is possible would the new cell be inserted above or below the one on which the action was initiated?
For the record I can add custom swipe actions to the cells, but the users feedback is they prefer an edit button.
Any light would be appreciated, all the Googling has gotten me is using a button to insert a new row, or adding custom swipe actions.
You need to implement the delegate method:
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle
Return .delete, .insert, or .none for a given index path. Normally only one row (typically first or last) would return .insert and the rest would return .delete. Return .none for any row that can't be inserted or deleted.
It's not uncommon that you also need to override the setEditing(_ editing: Bool, animated: Bool) method to add/remove an extra row just for the purposes of showing the green + (.insert) icon.
An alternative is to show the + icon in the nav bar instead of having a row with the insert icon.

tableView editing mode delete button (minus sign) not responding to tap - how do I fix this?

When my tableView goes into editing mode there's an icon on each side of my cell: the icon on the right is the default icon for rearranging the order of cells, and the icon on the left is the default icon for deleting a cell. I can easily interact with the rearranging icon with no problems, however, tapping on the delete icon gives no response. It only works when I do an awkward right swipe then left swipe on it. Below I've placed what I believe to be all the relevant code to my situation.
Some background information: I have three touch gestures in the view (a single tap, double tap, and long press). I've tried disabling them with conditions for when the editing mode is enabled. I've even tried deleting the touch gestures beforehand, but that didn't help. I thought it might be an auto layout issue that's not registering the area for the delete button, but the rearranging button works so shouldn't this? Both the my cell's leading and trailing constants are +10 to the view. Furthermore, isEditing is controlled by a UIButton. Finally, i have the tableView delegate set to self, and touch interaction when editing is enabled.
Any help would be appreciated. Thank you!
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if isEditing { return true }
return false
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if isEditing { return .delete }
return .none
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
countBeforeDeletingCell = dataSource.data.count
dataSource.data.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .none)
}
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = dataSource.data[sourceIndexPath.row]
dataSource.data.remove(at: sourceIndexPath.row)
dataSource.data.insert(movedObject, at: destinationIndexPath.row)
tableView.reloadData()
}
Hey If the you have use UITableViewController and using isEditing iOS defalut mode you have to override setEditing Mode and Changing Edit button Click.
iOS self.navigationItem.rightBarButtonItem = self.editButtonItem in editButtonItem is default UIViewController method. editButtonItem button Action override.
Swift Example:
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.reloadData()
}
it works for me on swift 5.7.May be you should config TrailingSwipeActionConfiguration like this:
unc tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive,
title: "Delete") { [weak self] _, _, complete in
//remove row in you data model here
tableView.deleteRows(at: [indexPath], with: .automatic)
complete(true)
}
deleteAction.backgroundColor = .red
return UISwipeActionsConfiguration(actions: [deleteAction])
}

swift: Table View Deletes wrong file

I want to delete an item from a table view.
First I added a filePath property on my class (that was missing)
Then I corrected the line of code to find the right filePath
the problem is solved but still I have the wrong file deleted so I check the sync of the arrays.
First, I make sure the table view knows what it shows and it appears the arrays are synced. I debug the code and I find that when I swipe to delete an item the code still deletes another file.
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableOfExpences.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellOfExpencesTableViewCell
let myOneExpense = self.tableOfExpences[indexPath.row]
if myOneExpense.size != nil {
//Arrangement Of the cell
//allocate the right image for each segment
} else {
cell.nameCellLabel?.text = "No Cost"
}
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
self.tableOfExpences.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
print("the removed from the table expence is the \(String(describing: tableOfExpences[indexPath.row].expenseID))")
print("We had bought a \(String(describing: tableOfExpences[indexPath.row].note))")
In my case there was a numerous things why the wrong file was deleted but the most tricky(when all the code seemed to be correct) was that first the file must be removed from the directory and then the cell from the table.
So just reversing the order of lines so that first to delete data from the file
try FileManager.default.removeItem(atPath: paths[indexPath.row])
and then to implement the
self.tableOfExpences.remove(at: indexPath.row)
solved the last great problem.

Remove Table View Cell from Table View with if statement

How do I remove a static table view cell by doing a if statement like this:
if ____ {
remove static cell
} else {
keep cell in tableview
}
The bolded part is what I need the code for. I searched the internet for an answer, but I could not find one. Thanks for the help! I'm using Swift 3
First, make sure to change cells to have Dynamic Properties, because static cells are hard-coded.
Second, you don't need an else statement. If the condition is true, delete the cell, otherwise do nothing. To delete a cell, use a function:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Cell deleted")
// delete any additional data from containers like arrays or dictionaries if needed
self.tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
If this is a static tableview you can't remove a cell. If you attempt to you'll probably fall into all sorts of issues. Your best solution is to set the cell's height to zero and hide it.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt:indexPath)
if indexPath == cellToHide {
cell.isHidden = true
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath == cellToHide {
return 0
}
return super.tableView(tableView, heightForRowAt: indexPath)
}

remove the delete button ⛔️ on table rows in edit mode

I am trying to learn Swift, but there is a problem in my project that drives me nuts.
I have a working list of data in a ViewController fed by parse.com. I managed to implement a swipe-feature that reveals buttons for both deleting and editing. That is working fine. Now I want the user to be able to reorder the cells. So I successfully implemented a button to put the table into editing-mode. My 2 problems with that are:
When I enter edit-mode I just want to be able to reorder the cells since editing and deleting is done via swipe (via "tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath)". How can I achive that the user doesn't see the 2 buttons for deleting and editing when in editing-mode and touching the delete-circle that is provided automatically?
Is it possible to remove the delete-circle altogether? Using "UITableViewCellEditingStyle.None" also disables the swipe-functionality.
Thanks in advance!
To avoid the round red delete button that appears when you put set UITableView isEditing to true at the left and does nothing when you click it, the minimum that worked for me was this (Swift 4, iOS 11)
// Avoid the round red delete button on the left of the cell:
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .none
}
I also have these functions, which probably interact:
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return savedTempTable.isEditing
}
// Including this function in the delegate enable left-swipe deleting
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if editingStyle == .delete {
savedConversions.remove(at: indexPath.row)
}
}
// Including this function enables reordering
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath,to destinationIndexPath: IndexPath)
{
let elem = savedConversions.remove(at: sourceIndexPath.row)
savedConversions.insert(elem, at: destinationIndexPath.row)
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
Although people can delete a row through swipe the delete-button in editing mode should not be removed. People may not know about the swipe gesture and by removing the delete button (which they already expect in editing mode) the app becomes more difficult to use.
If you really want to remove the delete button then you have to implement the delegate method tableView(_:editingStyleForRowAtIndexPath:). There you can return .None while the screen is in editing mode and .Delete while the screen is not.
To enable reordering you have to implement the data source methods tableView(_:canMoveRowAtIndexPath:) and tableView(_:moveRowAtIndexPath:toIndexPath:).
You follow this way to remove the delete Icon while editing:
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellAccessoryNone;
}

Resources