I have a UITableView that has two modes. When we switch between the modes I have a different number of sections and cells per section. Ideally, it would do some cool anima
I believe you can just update your data structure, then:
[tableView beginUpdates];
[tableView deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES];
[tableView insertSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES];
[tableView endUpdates];
Also, the "withRowAnimation" is not exactly a boolean, but an animation style:
UITableViewRowAnimationFade,
UITableViewRowAnimationRight,
UITableViewRowAnimationLeft,
UITableViewRowAnimationTop,
UITableViewRowAnimationBottom,
UITableViewRowAnimationNone,
UITableViewRowAnimationMiddle
Swift Implementation:
let range = NSMakeRange(0, self.tableView!.numberOfSections())
let indexSet = NSIndexSet(indexesInRange: range)
self.tableView!.reloadSections(indexSet, withRowAnimation: UITableViewRowAnimation.Automatic)
UITableView has a field called 'indexPathsForVisibleRows' that you can use to animate the visible rows using the 'reloadItemsAtIndexPaths' method.
guard let indexPaths = tableView.indexPathsForVisibleRows
else { return }
self.tableView.layoutIfNeeded()
self.tableView.reloadItemsAtIndexPaths(indexPaths, animationStyle: .automatic)
Native UITableView
animations in Swift
Insert and delete rows all at once with tableView.performBatchUpdates
so they occur simultaneously. Building on the answer from @iKenndac use methods such as:
tableView.insertSections
tableView.insertRows
tableView.deleteSections
tableView.deleteRows
Ex:
tableView.performBatchUpdates({
tableView.insertSections([0], with: .top)
})
This inserts a section at the zero position with an animation that loads from the top. This will re-run the cellForRowAt
method and check for a new cell at that position. You could reload the entire table view this way with specific animations.
Re: the OP question, a conditional flag would have been needed to show the cells for the alternate table view state.
The way to approach this is to tell the tableView to remove and add rows and sections with the
insertRowsAtIndexPaths:withRowAnimation:
,
deleteRowsAtIndexPaths:withRowAnimation:
,
insertSections:withRowAnimation:
and
deleteSections:withRowAnimation:
methods of UITableView.
When you call these methods, the table will animate in/out the items you requested, then call reloadData on itself so you can update the state after this animation. This part is important - if you animate away everything but don't change the data returned by the table's dataSource, the rows will appear again after the animation completes.
So, your application flow would be:
[self setTableIsInSecondState:YES];
[myTable deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES]];
As long as your table's dataSource methods return the correct new set of sections and rows by checking [self tableIsInSecondState]
(or whatever), this will achieve the effect you're looking for.