Invalid update: invalid number of rows in section UITableView problem - ios

I am playing with a table as below (I've seen multiple threads on this topic but couldn't answer my question):
func numberOfSections(in _: UITableView) -> Int {
3
}
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 3
} else if section == 1 {
return 4
} else {
return 2
}
}
Then after clicking on a cell I want a new cell inserted into the same section at row index 0. I wrote the below:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.insertRows(at: [IndexPath(row: 0, section: indexPath.section)], with: .left)
}
I get this error:
Exception NSException * "Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)."
I assume I should somehow update the data source, but since in my case I return const values for rows in sections is there a way to update the the number of rows in section? (the numberOfRows in section only returns immutable value). Thank you

in my case I return const values
There you go! If you are going to modify the number of rows you need variables
For example
var sections = [3,4,2]
func numberOfSections(in _: UITableView) -> Int {
return sections.count
}
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
sections[indexPath.section] += 1
tableView.insertRows(at: [IndexPath(row: 0, section: indexPath.section)], with: .left)
}

Related

Collapsable Sections: [Assert] Unable to determine new global row index for preReloadFirstVisibleRow (0)

I'm implementing collapsable section headers in a UITableViewController.
Here's how I determine how many rows to show per section:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.sections[section].isCollapsed ? 0 : self.sections[section].items.count
}
There is a struct that holds the section info with a bool for 'isCollapsed'.
Here's how I'm toggling their states:
private func getSectionsNeedReload(_ section: Int) -> [Int]
{
var sectionsToReload: [Int] = [section]
let toggleSelectedSection = !sections[section].isCollapsed
// Toggle collapse
self.sections[section].isCollapsed = toggleSelectedSection
if self.previouslyOpenSection != -1 && section != self.previouslyOpenSection
{
self.sections[self.previouslyOpenSection].isCollapsed = !self.sections[self.previouslyOpenSection].isCollapsed
sectionsToReload.append(self.previouslyOpenSection)
self.previouslyOpenSection = section
}
else if section == self.previouslyOpenSection
{
self.previouslyOpenSection = -1
}
else
{
self.previouslyOpenSection = section
}
return sectionsToReload
}
internal func toggleSection(_ header: CollapsibleTableViewHeader, section: Int)
{
let sectionsNeedReload = getSectionsNeedReload(section)
self.tableView.beginUpdates()
self.tableView.reloadSections(IndexSet(sectionsNeedReload), with: .automatic)
self.tableView.endUpdates()
}
Everything is working and animating nicely, however in the console when collapsing an expanded section, I get this [Assert]:
[Assert] Unable to determine new global row index for preReloadFirstVisibleRow (0)
This happens, regardless of whether it's the same opened Section, closing (collapsing), or if I'm opening another section and 'auto-closing' the previously open section.
I'm not doing anything with the data; that's persistent.
Could anyone help explain what's missing? Thanks
In order for a tableView to know where it is while it's reloading rows etc, it tries to find an "anchor row" which it uses as a reference. This is called a preReloadFirstVisibleRow. Since this tableView might not have any visible rows at some point because of all the sections being collapsed, the tableView will get confused as it can't find an anchor. It will then reset to the top.
Solution:
Add a 0 height row to every group which is collapsed. That way, even if a section is collapsed, there's a still a row present (albeit of 0px height). The tableView then always has something to hook onto as a reference. You will see this in effect by the addition of a row in numberOfRowsInSection if the rowcount is 0 and handling any further indexPath.row calls by making sure to return the phatom cell value before indexPath.row is needed if the datasource.visibleRows is 0.
It's easier to demo in code:
func numberOfSections(in tableView: UITableView) -> Int {
return datasource.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasource[section].visibleRows.count == 0 ? 1 : datasource[section].visibleRows.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
datasource[section].section = section
return datasource[section]
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if datasource[indexPath.section].visibleRows.count == 0 { return 0 }
return datasource[indexPath.section].visibleRows[indexPath.row].bounds.height
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if datasource[indexPath.section].visibleRows.count == 0 { return UITableViewCell() }
// I've left this stuff here to show the real contents of a cell - note how
// the phantom cell was returned before this point.
let section = datasource[indexPath.section]
let cell = TTSContentCell(withView: section.visibleRows[indexPath.row])
cell.accessibilityLabel = "cell_\(indexPath.section)_\(indexPath.row)"
cell.accessibilityIdentifier = "cell_\(indexPath.section)_\(indexPath.row)"
cell.showsReorderControl = true
return cell
}

How to create a section of StaticTableView with variable row?

Basically I have a view controller with a static table view with 2 sections. The first section will have 1 row and represent a main category.
I want the second section to have a variable amount of rows depending on how many entries the user has for that category. So if the category is "Activities" and they have "Baseball, softball" as activities, I want there to be 2 rows in that section.
How do you do this? It keeps crashing when I code it.
You can try this.....
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return YourDataSource.count
}
}
and on your cellforrowatindex
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
//Do your stuff for the static section
} else {
//Do your stuff for the dynamic section
}
}

Unable to delete row from table view

I have a table view with a certain number of rows. With a button on the same ViewController, I want to pop out one of the tableView rows. However, I am unable to do so. Note that I am not using editing style of table view but using a button on the same ViewController to delete a row from the tableView.
func postAction() {
postTable.deleteRows(at: [IndexPath(row: 0, section: 0)] , with: .fade)
}
However this results in crash. I am not sure why is this happening and how I should correct this. I intend to delete the first row from the only section here in the tableView (postTable)
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.
The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
My code:
postTable.delegate = self
postTable.dataSource = self
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = JobPostCellView(style: UITableViewCellStyle.default , reuseIdentifier: "PostCell")
cell.delegate = self
cell.name = arr[indexPath.row]
return cell
}
try this
func postAction() {
let indexPath = IndexPath(row: 0, section: 0)
yourmodel.remove(at: indexPath.row)//update your model also here
postTable.deleteRows(at: [indexPath] , with: .fade)
}
this may be happenig because you tableview row is not matching with the returning rows from number of rows in section method of your data source
for example
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
if you are returning 10 in your numberOfRowsInSection then there will be 10 rows in table
now you are deleting 1 row from it so the rows will be 9 but your numberOfRowsInSection method still returning 10 so this will create inconsistency so you have to update your count in numberOfRowsInSection section to return 9
and if you are using dynamic array than you have to delete it from your array also like in answer

Swift - Movable rows in tableView only within a section, not between

Is there a way to prevent cells in a tableView from being moved to a different section?
The sections have data for different types of cells, so the app crashes when the user tries to drag a cell into a different section.
I would like to only allow the user to move a cell inside the section, and not in between sections.
Relevant code is below:
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let reorderedRow = self.sections[sourceIndexPath.section].rows.remove(at: sourceIndexPath.row)
self.sections[destinationIndexPath.section].rows.insert(reorderedRow, at: destinationIndexPath.row)
self.sortedSections.insert(sourceIndexPath.section)
self.sortedSections.insert(destinationIndexPath.section)
}
You will need to implement the UITableViewDelegate method targetIndexPathForMoveFromRowAt.
Your strategy will be to allow the move if the source and destination section are the same. If they aren't then you can return either row 0, if the proposed destination section is less than the source section or the last row of the section if the proposed destination section is greater than the source section.
This will constrain the move to the source section.
override func tableview(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
let sourceSection = sourceIndexPath.section
let destSection = proposedDestinationIndexPath.section
if destSection < sourceSection {
return IndexPath(row: 0, section: sourceSection)
} else if destSection > sourceSection {
return IndexPath(row: self.tableView(tableView, numberOfRowsInSection:sourceSection)-1, section: sourceSection)
}
return proposedDestinationIndexPath
}
You can retarget the proposed destination for restriction by implementing the tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath: method
func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
// Finds number of items in source group
let numberOfItems = self.tableView(tableView, numberOfRowsInSection: sourceIndexPath.section)
// Restricts rows to relocation in their own group by checking source and destination sections
if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
/*
if we move the row to the not allowed upper area, it is moved to the top of the allowed group and vice versa
if we move the row to the not allowed lower area, it is moved to the bottom of the allowed group
also prevents moves to the last row of a group (which is reserved for the add-item placeholder).
*/
let rowInSourceSection = (sourceIndexPath.section > proposedDestinationIndexPath.section) ? 0 : numberOfItems - 1;
return IndexPath(row: rowInSourceSection, section: sourceIndexPath.section)
}
// Prevents moves to the last row of a group (which is reserved for the add-item placeholder).
else if (proposedDestinationIndexPath.row >= numberOfItems) {
return IndexPath(row: numberOfItems - 1, section: sourceIndexPath.section)
}
// Passing all restrictions
return proposedDestinationIndexPath
}

How to hide UITableViewSections in Swift?

I have a static grouped table view that has 5 sections (all the sections have headers, no footers). I created all of this using a Storyboard. Now, how can I hide the first/top UITableViewSection (including the header). I tried making an outlet to the UITableViewSection but it tells me that it is not valid (undeclared type):
#IBOutlet var section: UITableViewSection!
I did it this way because I was planning on doing:
section.hidden = true
Can it not be done this way?
My delegates and data sources are set up 100% correctly.
Swift 5:
You can use the delegate method heightForHeaderInSection
:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if (section == 0) {
return 0.0
}
return UITableView.automaticDimension
}
Earlier than Swift 5: Use UITableViewAutomaticDimension instead of UITableView.automaticDimension
If it's not working with height 0.0, use height 0.1
If you want no cells in a particular section, use the delegate method:
func numberOfRowsInSection(section: Int) -> Int {
if (section == 0) {
return 0
}
else {
// return the number of rows you want
}
}
Or to a neater switch-case syntax:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return 0.0
default:
return UITableView.automaticDimension
}
}
I tested both and they are working fine.
I also wish you could just make an #IBOutlet to a section and hide it, but sadly it seems not, so...
Based on various suggestions here, I've established the following, which doesn't require any interfering with explicit size values, and preserves whatever you may have set on a storyboard/XIB already. It just makes the header nil and row count 0 for any section you want to hide (which results in a size of 0.0).
Obviously, you can configure sectionShouldBeHidden to work however you need; hiding #1 & #3 are just arbitrary examples.
Swift v5
private func sectionShouldBeHidden(_ section: Int) -> Bool {
switch section {
case 1, 3: return true
default: return false
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if sectionShouldBeHidden(section) {
return nil // Show nothing for the header of hidden sections
} else {
return super.tableView(tableView, titleForHeaderInSection: section) // Use the default header for other sections
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if sectionShouldBeHidden(section) {
return 0 // Don't show any rows for hidden sections
} else {
return super.tableView(tableView, numberOfRowsInSection: section) // Use the default number of rows for other sections
}
}
Update: Unfortunately, the above is only enough if the style of the table view is Plain. When it's Grouped, there's also additional space added between each section, which needs taking care of too.
This extra space is the section's footer, so can be handled like so:
override public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if sectionShouldBeHidden(section) {
return CGFloat.leastNormalMagnitude // Use the smallest possible value for hidden sections
} else {
return super.tableView(tableView, heightForFooterInSection: section) // Use the default footer height for other sections
}
}
I tried all the solutions here with no success. At the end, adding these delegate methods this one worked:
Swift 5:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 4 ? 0 : return super.tableView(tableView, numberOfRowsInSection: section)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 4 ? 0.1 : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return section == 4 ? 0.1 super.tableView(tableView, heightForFooterInSection: section)
}
Note that you need to return 0.1 in height, returning 0 won't do it.
0.0 did not work for me. I had to do this in order to make it work.
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return 0.01
default:
return UITableViewAutomaticDimension
}
}
For group UITableView with static cells only this solution works:
self.tableView.sectionHeaderHeight = 0;
self.tableView.sectionFooterHeight = 0;
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let count = self.tableView(tableView, numberOfRowsInSection: section)
if count == 0 {
return CGFloat(Double.leastNormalMagnitude)
}
return 44.0
}
For anyone wanting to hide sections because they are using a static grouped tableView with a dynamic number of sections, the solution below may be of help. In my case, each section with data to display needed to have a custom header. Any section that did not have data, needed to be hidden fully.
The answer above was of great help in my scenario. However, for those who don't always know which section(s) will need to be hidden here is a solution for you extending on the above.
In my scenario, I have up to 12 entries in an array that I want to show in up to 12 sections (amongst other sections in a grouped tableView). If there are less than 12 entries to display, I want to hide the unnecessary sections by giving them 0 height and 0 rows. I also wanted to hide the headerView.
To do this, I did the following:
Set up your tableView as per the excellent answer #sasquatch gave
above.
In the numberOfRowsInSection(section: Int) and tableView(_
tableView: UITableView, heightForHeaderInSection section: Int) functions, check whether the rows/height should be 0.
In my case, I was using sections 1 - 12 for my dynamic data so I used code as below:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//For section 0 and 13, just 1 row is ok
if section == 0 || section == 13 {
return 1
}
//For sections 1 - 12, determine if we have data to populate it, or if we should hide it
if section <= dynamicDataToDisplay.count {
return 2
}
//If it's section 1 - 12, but we don't have a corresponding data entry in dynamicDataToDisplay, then just return 0 rows
return 0
}
The code for the heightForHeader function is similar in logic:
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return 45.0
case 13:
return UITableViewAutomaticDimension
default:
if dynamicDataToDisplay.count >= section {
return 25.0
} else {
return 0.0
}
} //end switch
}
Even after setting up these functions, I found that I was still getting headers appearing for the sections I wanted to hide. I guess I thought that viewForHeaderInSection would not be called if the numberOfRows was 0 and heightOfHeader was also 0, but it was still being called.
Adding the following helped ensure that the header wasn't unnecessarily created:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//set up header for dynamic data sections
if 1 ... 12 ~= section {
if tableView.numberOfRows(inSection: section) == 0 {
return nil
}
//Continue with the header set up for valid sections with rows to display data
......
}
}
This solution might help anyone who is still getting a header being created despite its height and rows being set to 0.

Resources