How to delete table view row from custom cell? - ios

I have a custom table view cell with two buttons. If either one is pressed, I want the table view to delete the row. I already know the code for that:
myArray.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
I just would like to call this from my custom cell. I have it set up like so:
#IBAction func handleDecline(sender: AnyObject)
{
// Remove table view row
}
#IBAction func handleApprove(sender: AnyObject)
{
// Remove table view row
}
How would I go about doing that?

You should not handle deletion of a cell from the cell itself. It violates MVC pattern. Events should be delegated to the view controller and handled there with deleteRows method like this:
tableView.deleteRows(at: [indexPath], with: .fade)
Also tableView's dataSource must be updated accordingly, otherwise app will crash.
Here you can find an example of how you can delegate an event from cell to view controller

Related

Inserting rows into UITableView using data that's passed from another view controller via delegate

I've set the delegate properly so that two different view controllers communicate with each other. There's no problem in passing the data (I've checked and the data passing is successful). The only problem I'm having is when I use the following code to insert a new row:
let indexPath = IndexPath(row: paymentMethodArray.count - 1, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.reloadData()
it doesn't do anything (it doesn't update the row but data is passed and appended to the array). This code however works when I'm calling the function from the same view controller without having to come back from another view controller (data is sent from AddPaymentViewController to this view controller, AddPaymentViewController is the vc that comes after the current vc). My guess is that my code for destination segue or view controller is wrong.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let addPaymentViewController = segue.destination as! AddPaymentViewController
addPaymentViewController.delegate = self
}
If you need more information on this I can add on to it. Just let me know, thanks.
Maybe double check that number of rows in the table have updated after you have added more rows.
func tableView(UITableView, numberOfRowsInSection: Int)
Also check if you would like to use tableView.beginUpdates() and tableView.endUpdates() around insertion of new cell to the table.

tableView deleting more than one cell with deleteRowsAtIndexPaths method

I have a table view with two custom cells, one of those cells has custom button (subclassed uibutton to hold the indexpath). I created a custom delegate for the cell with the custom button, here is the code of the delegate method:
func indexOfClassDeletedInTableView(path:NSIndexPath, table:UITableView) {
let classToDelete = self.classesScheduled[path.row]
ManagedObjectsController.sharedInstance.deleteScheduledClass(classToDelete) { (succedeed) in
if (succedeed == true) {
NSNotificationCenter.defaultCenter().postNotificationName(self.itemSuccesFullyDeletedFromPersonalView, object: nil)
self.classesScheduled.removeAtIndex(path.row)
table.deleteRowsAtIndexPaths([path], withRowAnimation: .Fade)
} else {
print("failed to delete class from personal schedule")
}
}
}
the problem is that the first time the method gets called, the table deletes the cell at the indexpath given and the one below it. After the first call it works fine and suddenly the extra cell deleted reappears. The custom delegate method (indexOfClassDeletedInTableView) is in my datasource. Thank you in advance.

UITableView issue, it scrolls halfway up after updating or inserting a new cell

My TableView is doing some kind of auto-scrolling after any kind of updates are applied to it. If I were to append a new element to the array that contains the items which are presented in the UITableView, for some reason my Table View scrolls up somewhat randomly up around 50% up the middle of the contents of the TableView.
Here's the function that deals with updating, not inserting an item into the Table View:
func updateLastMessage() {
var section = msgSections.count - 1
var row = msgSections[section].msg.count - 1
let indexPath = NSIndexPath(forRow: row, inSection: section)
self.tableView.beginUpdates()
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
}
This function above works perfectly, but after I call reloadRowsAtIndexPaths on self.tableView, the table view automatically scrolls up 50% of the contents of the Table View. I get exactly the same result if I were to insert an item instead:
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
Also, if I were to comment out both beginUpdates() and endUpdates(), there seems to be no effect to the scrolling.
I only know of one hack to somewhat get around this issue by using setContentOffset to return the scroll position back to where it was before a message was updated, or a new message is inserted:
func updateLastMessage() {
let currentContentOffset = self.tableView.contentOffset
var section = msgSections.count - 1
var row = msgSections[section].msg.count - 1
let indexPath = NSIndexPath(forRow: row, inSection: section)
self.tableView.beginUpdates()
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
self.tableView.setContentOffset(currentContentOffset, animated: false)
}
This hack doesn't work in my favor, because it scrolls slowly to the top and then jolts back to where it was which looks kind of bad.
Does anyone know exactly what could be the mechanism that's causing the TableView to scroll up so much after any appended item or updated item??
It seems to work perfectly and the animation looks very nice as but only when there aren't any items in the table view.
Never call reloadRowsAtIndexPaths: withRowAnimation: inside beginUpdates() and endUpdates().
The tableView will automatically call the necessary reloading of rows at the end of endUpdates().
Just call beginUpdates() and endUpdates() without any code inside. It'll work.

Add completion for deleteRowAtIndexPaths with an extension or didEndDisplayingCell

I'd like to do something after deleteRowsAtIndexPaths has finished it's animation.
I can achieve this by wrapping it in animateWithDuration but it doesn't feel like the right way of doing it.
Another way is using didEndDisplayingCell but I can't update the section here or else it will get in an infinite loop.
What I'm trying to do is:
Delete a cell by swiping it
Remove it from my data model
Delete the row with deleteRowsAtIndexPaths
After the row has been deleted and animation has ended:
Reload sections by calling reloadSections
The code I'm using:
func deleteObject(ojbectName: String) {
let indexPath = // create indexPath
// Delete the item in data model and table
myData.removeAtIndex(index)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Left)
// Reload section after row animation has ended
let indexSet = NSIndexSet(indexesInRange: NSMakeRange(myData[indexPath.section].startIndex, myData[indexPath.section].endIndex))
tableView.reloadSections(indexSet, withRowAnimation: .None)
}
I tried creating an extension for UITableView that didn't go well. Is there someone who can tell me how to create one or how to use didEndDisplayingCell so I can reload the section after the animation has ended?
Try implementing didTransitionToState in your subclassed UITableViewCell. Check out the Apple docs on this.
`

Dynamic cell height causing bounce effect when calling reloadRowsAtIndexPaths method

Background: In a tableView, each cell contains a button shown as an image. The effect I wanna show is that when I click the image(button actually), the button's image change to another one.
Bug: Say there are many data (over one page), and if I click one cell's button, the button's image will change BUT with a side effect that the whole tableView will first scroll up a little bit(like a bounce effect) then scroll down to the former place.
What I've done:
in ViewDidLoad method:inboxListTableView.estimatedRowHeight = 60
inboxListTableView.rowHeight = UITableViewAutomaticDimension
When I clicked the button (true and false represent different image and the definition in tableView(cellForRowAtIndex:) method):
let cell = sender.superview?.superview as InboxListCellTableViewCell
if let indexPath = inboxListTableView.indexPathForCell(cell) {
let actionToUpdate = actions[indexPath.row]
actionToUpdate.imageButton = !actionToUpdate.imageButton.boolValue
var e: NSError?
if !MOContext.save(&e) {
println(e?.description)
}
}
Then in Fetch Result Controller Delegate method:
func controllerWillChangeContent(controller: NSFetchedResultsController) {
inboxListTableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
switch type {
case .Insert:
inboxListTableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case .Delete:
inboxListTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .Update:
inboxListTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
default:
inboxListTableView.reloadData()
}
actions = controller.fetchedObjects as [Action]
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
inboxListTableView.endUpdates()
}
I think the bug may caused by two aspects: CoreData and Self sizing cells (dynamic cell height). Because I didn't hit the bug when I use array to hold actions ([Action]) instead of CoreData. However, when I comment inboxListTableView.rowHeight = UITableViewAutomaticDimension this code, it didn't "bounce back/ scroll up" but the height of the cell is fixed.
Any ideas? Anything can help! Thank you:)
I had the exact same problem: a little bounce when using dynamic cell heights. The difference in my case is that I didn't use NSFetchedResultsController and I also changed the heights of the cells (expand and collapse them).
After a lot of experimenting I've found a simple solution. Just call scrollToRowAtIndexPath after reloadRowsAtIndexPaths. It worked for me.
tableView.reloadRows(at: [indexPath], with: .none)
tableView.scrollToRow(at: indexPath, at: .none, animated: true)
I call this code when I expand and collapse the cells.
I hope you can use this in your project.
I think the pragmatic solution to your problem is to simply not use the NSFetchedResultsControllerDelegate method for this particular update.
You can change the image of the button directly in the button handler. You have to check for this situation in the .Update case of the fetched results controller delegate and make sure you don't call the reloadRowsAtIndexPaths method.
Now you are avoiding the automatic UI-update mechanism and the issue should not occur.
BTW, it is very bad practice to rely on the table view cell's view hierarchy for accessing the index path (superview.superview...). A few years ago, Apple changed the way cells work and code that relied on similar paradigms broke. The same with collection view cells.
Instead, do something like this:
func buttonHandler(sender: UIButton) {
let point = sender.convertPoint(CGPointZero, toView:self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(point)
}

Resources