问题
I have a dataset that I want to display in an UITableView. All new sets of data I want to insert as a section 0. Often, I will get many sets, and then I want to push them on the top one at a time. This looks like
tableView.beginUpdates()
repeat {
data.append(dataProvider.nextDataSet())
tableView.insertSections(NSIndexSet(index:0), withRowAnimation: .Automatic)
} while dataProvider.hasMoreData
tableView.endUpdates()
While my data
array is exactly like I would like it, my app crashes saying something like:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (5) must be equal to the number of sections contained in the table view before the update (0), plus or minus the number of sections inserted or deleted (2 inserted, 0 deleted).'
I have made a little sample project on GitHub that recreates this problem by doing
numSections += 1
tableView.insertSections(NSIndexSet(index:0), withRowAnimation: .Automatic)
five times (link) where numSections is the number of sections, and the number of rows is always three per section. Again it says that I have inserted only 2 sections, while in fact I did insert 5.
What is it I am misunderstanding here? Why does tableView think I only gave it 2 new sections? Of course, if I only give it 2 sections, it thinks I only gave it 1. :-I
回答1:
The section index you insert doesn't matter as far as the order of your data being displayed is concerned, that's controlled by your data array. You should insert the sections at different indexes, so use the numSections
variable to control that.
I expect if you move the begin and end updates into the loop it will also work. The problem is you don't know how the table view works internally, the issue you see isn't documented as far as I know, but it's illogical to insert sections at indices which don't match your underlying data.
回答2:
The insertSections will be actually executed at the end of endUpdates()
. So in actual scenario, the sections isn't inserted and you are specifying as the sections have been increased.
This will work. If you know the number of sections to be inserted, then use this method
tableView.beginUpdates()
numSections += 5
tableView.insertSections(NSIndexSet(indexesInRange: NSMakeRange(0, 5)), withRowAnimation: .Automatic)
tableView.endUpdates()
The above code is for the github code. It can be altered for your actual code. Do not call insertSections()
in a loop or multiple times.
来源:https://stackoverflow.com/questions/35403808/uitableview-multiple-insertsections-to-same-index