Here's what I'm trying to do:
UITableView in editing mode with 2 sections.
User can move cells from second section into first and vice versa.
In the first section user can reorder cells as he wants.
In the second section positioning of cells is fixed, so if user moves a cell from first section into second, it should move to a specific place, not where user want.
For implementing this behavior I have 2 arrays: one for first section and one for second section (not sure if it's the best choice).
Here's the code that controls where user should move a cell:
func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
if proposedDestinationIndexPath.section == 1 {
let item = (sourceIndexPath.section == 0 ? firstSectionItems[sourceIndexPath.row] : secondSectionItems[sourceIndexPath.row]).item
return NSIndexPath(forRow: item.displayOrder.integerValue, inSection: 1)
}
return proposedDestinationIndexPath
}
Here's the code for moving items between sections:
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let section = (source: sourceIndexPath.section, destination: destinationIndexPath.section)
switch section {
case (0, 0):
let itemToMove = firstSectionItems.removeAtIndex(sourceIndexPath.row)
itemToMove.item.order = destinationIndexPath.row
firstSectionItems.insert(itemToMove, atIndex: destinationIndexPath.row)
case (1, 1):
let itemToMove = secondSectionItems.removeAtIndex(sourceIndexPath.row)
secondSectionItems.insert(itemToMove, atIndex: destinationIndexPath.row)
case (1, 0):
let itemToMove = secondSectionItems.removeAtIndex(sourceIndexPath.row)
itemToMove.item.order = destinationIndexPath.row
firstSectionItems.insert(itemToMove, atIndex: destinationIndexPath.row)
case (0, 1):
let itemToMove = firstSectionItems.removeAtIndex(sourceIndexPath.row)
itemToMove.item.order = -1
secondSectionItems.insert(itemToMove, atIndex: destinationIndexPath.row)
default:
break
}
DatabaseConnector.saveContext()
}
Problem is that if I have several items in the first section and I try to move last one into the second section, it crashes when I drop the cell on the second section and shows me EXC_BAD_ACCESS on App Delegate with no output to console.
Debug navigator doesn't tell me much, moveRowAtIndexPath: doesn't get called. The last method that gets called is -[UISectionRowData insertRowAtIndex:inSection:rowHeight:tableViewRowData:].
Sometimes I get a strange message in console when it crashes:
warning: could not load any Objective-C class information from the
dyld shared cache. This will significantly reduce the quality of type
information available.
I'm using Swift 2.
Well, the problem was in displayOrder of an item in tableView(_:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:) method.
If you have, say, 5 elements in an array and the displayOrder of the one you want to insert is, say, 7, it'll crash because last indexPath.row in that section will be 5, but you are trying to insert with indexPath.row = 7, which is can't happen. You can insert with indexPath.row = 6 though, because it's the next after the last indexPath in the table view.
So this is how that method now looks like:
func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
if proposedDestinationIndexPath.section == 1 {
let item = (sourceIndexPath.section == 0 ? firstSectionItems[sourceIndexPath.row] : secondSectionItems[sourceIndexPath.row]).item
let rowIndex = item.displayOrder > secondSectionItems.count ? secondSectionItems.count : item.displayOrder
return NSIndexPath(forRow: rowIndex, inSection: 1)
}
return proposedDestinationIndexPath
}
And it works just fine.
(stupid mistake :-/)
Related
I am building an iOS app, basically the user create an item by pressing the "+" button and then the app should put the new item in according section of the table based on the location of the item. However I got the error: Invalid update: invalid number of rows in section 1. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update. Here is my code, thank you
let sections = ["Bathroom", "Bedroom", "Dining Room", "Garage", "Kitchen", "Living Room"]
#IBAction func addNewItem(_ sender: UIBarButtonItem) {
/*
//Make a new index path for the 0th section, last row
let lastRow = tableView.numberOfRows(inSection: 0)
let indexPath = IndexPath(row: lastRow, section: 0)
//insert this new row into the table
tableView.insertRows(at: [indexPath], with: .automatic)*/
//Create a new item and add it to the store
let newItem = itemStore.createItem()
var Num: Int = 0
if let index = itemStore.allItems.index(of: newItem) {
switch newItem.room {
case "Bathroom":
Num = 0
print("I am in here")
case "Bedroom":
Num = 1
case "Dining Room":
Num = 2
case "Garage":
Num = 3
case "Kitchen":
Num = 4
case "Living Room":
Num = 5
default:
Num = 0
print("I am in Default")
}
let indexPath = IndexPath(row: index, section: Num)
tableView.insertRows(at: [indexPath], with: .automatic)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemStore.allItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//create an instance of UITableViewCell, with default appearance
//let cell = UITableViewCell(style: .value, reuseIdentifier: "UITableViewCell")
//get a new or recycled cell
//if indexPath.row < itemStore.allItems.count {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell
//Set the text on the cell with the decription of the item
//that is at the nth index of items, where n = row this cell
//will appear in on the table view
let item = itemStore.allItems[indexPath.row]
if item.name == "" {
cell.nameLabel.text = "Name"
} else {
cell.nameLabel.text = item.name
}
if item.serialNumber == nil {
cell.serialNumberLabel.text = "Serial Number"
} else {
cell.serialNumberLabel.text = item.serialNumber
}
cell.valueLabel.text = "$\(item.valueInDollars)"
cell.roomLabel.text = item.room
if item.valueInDollars < 50 {
cell.valueLabel.textColor = UIColor.green
}else if item.valueInDollars >= 50 {
cell.valueLabel.textColor = UIColor.red
}
cell.backgroundColor = UIColor.clear
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let LocationName = sections[section]
return LocationName
}
thank you so much for your time!
and this is how I create item
#discardableResult func createItem() -> Item {
let newItem = Item(random: false)
allItems.append(newItem)
return newItem
}
The problem is that you should insert the item in the array first:
itemStore.allItems.append(newItem)
Also, there is a difference between sections and rows in numberOfRowsInSection(return number of rows for every section) you have a switch that returns the same number, it should be
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemStore.allItems.count
}
Edit :
The problem is when the table loads there is 0 rows for all the sections ( itemStore.allItems.count is zero ), when you try to insert a row say at section 0 , row 0 -- the dataSource must be updated only for that section , which is not happen in your case as it's the same array that is returned for all sections , so you must either have an array of array where inner array represent number of rows so addition/deletion from it doesn't affect other ones ,,,,, or lock the insert to say section 0 like this
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 0 ) {
return itemStore.allItems.count
}
return 0
}
in this edit i inserted in 2 sections 0 and 2 with no crash because i handled numberOfRowsInSection to return old numbers for old section that why to be able to insert in all sections you must have a different data source array or manage from numberOfRowsInSection , see edited demo here Homepwner
Instead of setting footer in viewDidLoad implement this method
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if(section == 5 ) {
let textLabel = UILabel()
textLabel.text = "No more Item"
return textLabel
}
return nil
}
There is something terribly wrong with your data source. Your numberOfRow for all sections is the same. i.e. itemStore.allItems.count. Which means you are setting the same number of rows in each section.
The main issue is, while adding a new item, you are inserting a new row in the specific section which means
new number of rows for section = previous number of rows in section +
1
However, there is no addition in the data source.
So according to the code, you have inserted a new row, but your data source has one record less since you didn't add the item there.
So I would like you do the following in order of these steps :
Add item in required data source.
inserRowInSection
Update : Remove the condition in cellForRowAtIndexPath :
if indexPath.section <= 1 and it's else block. You don't need that. If number of sections is less than 1, it won't be called. Moreover it's the else block which is getting called all the time because you already have sections in your code. So if case will never be called.
So I got the issue. In itemStore.createItem() the value for room is always Room. In the switch-case, you never have Room case. So it always falls in default case. You need to fix that.
#Jacky.S I downloads your code and try to debug it.Fist look our error properly.
reason: 'Invalid update: invalid number of rows in section 1. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (0)
So It says before update, your sections has 0 rows. Now you try to update you tableview using this piece of code.
print(indexPath)
tableView.insertRows(at: [indexPath], with: .automatic)
I just added the print statement for debugging purpose and it prints [0, 0] .So you say your tableview to insert 0th row on section 0.
Now when you insert any row into tableview it calls the delegate method.Now look at the below delegate method.
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
if section == 0{
print("0",itemStore.allItems.count)
}
if section == 1{
print("1",itemStore.allItems.count)
}
// print(itemStore.allItems)
return itemStore.allItems.count
}
In your code you just return itemStore.allItems.count.I added the above code for debugging.Now look that itemStore.allItems.count always return 1.So for first section it works perfectly because few times ago you insert a row in first section whose index is [0 = row, 0 = section].So you previously returned rows for section 0 is equal to the recently return rows for section 0.But When it comes for section 1 you previously return no row that means your section 1 has no rows in previous but in your above delegate method you also return 1 row for section 1.Which is conflicting because in previous you never update or return any rows for section 1.That's why you code crash and and say that
your number of rows contained in an existing section after the update is 1 which must be equal to the number of rows contained in that section before the update. Which is 0.
So this is the explanation for you crash.
Now, to recover from crash your allItems should be a dictionary or an array of array.
var allItems = [[Item]]()
or
var allItems = ["String":[Item]]()
guess allItems element is something like this
allItems = ["bathroom":[item1, item2, item3],"bedroom":[item1, item2, item3, item4]]
so here you have 2 section one is bathroom and another is bedroom.First section have 3 row and second one have 4 row and in you tableview delegate method you have to return 3 for section 0 and 4 for section 1
Background
The story is come from the second example of the book IOS apprentice (Ed. 6 2016)
A UItableView with two section is created. In storyboard the following content had been designed: section 0 has one row fulfilled with one static cell, section 1 has two row full filled with two static cell.
What to achieve
When tap the last row of section 1 (ie, the dueDate row in picture A) a new cell with a UIDatePicker will be inserted into the tableView (please see picture B)
How does the author solve the problem
A UITableViewCell filled with a UIDatePicker is added in to the scene dock in storyBoard (please see picture C), the new tableCell will be added into the table when dueDate row is tapped
Table view with static cells does not have a data source and therefore does not use the function like “cellForRowAt”. In order to insert this cell into the table the following data source functions had been overridden
tableView(_:numberOfRowsInSection:)
tableView(_:cellForRowAt:)
tableView(_:heightForRowAt:)
tableView(_:indentationLevelForRowAt:)
Problem
the function tableView(_:indentationLevelForRowAt:) really confuse me a lot! And here is the full code
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
var newIndexPath = indexPath
if indexPath.section == 1 && indexPath.row == 2 {
newIndexPath = IndexPath(row: 0, section: indexPath.section)
}
return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
}
Question
What is the meaning of this function? What's the purpose of it? I've read the document, but I didn't get much information.
When the third row/datePicker cell is inserted (indexPath.section == 1 && indexPath.row == 2) why the function will indent the first row newIndexPath = IndexPath(row: 0, section: indexPath.section) ?
Implementing tableView(_:indentationLevelForRowAt:) allows you to display the table rows in a hierarchal / tree-view type format. As in:
Level 1
Sub-Level 1a
Sub-Level 1b
Level 2
Sub-Level 2a
Sub-sub-level 2aa
Sub-sub-level 2ab
etc...
Commonly, one might use:
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
if let myObj = myData[indexPath.row] as? MyObject {
return myObj.myIndentLevel
}
return 0
}
For the example you present, without reading the book...
It would appear the author decided that the new row (2) that contains the UIDatePicker should have the same indent level as the first row (0) in the section. If it's not the row 2, then return the default / current indentation level.
Although, the intent of
var newIndexPath = indexPath
if indexPath.section == 1 && indexPath.row == 2 {
newIndexPath = IndexPath(row: 0, section: indexPath.section)
}
return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
might seem a little more obvious / clear with
newIndexPath = IndexPath(row: 0, section: 1)
since it is already limiting this to section == 1.
Hi friends of StackOverflow.
I have a chat screen on my app and I it perform a insertion and deletion based on the actual size of the an Array. Look this:
func addObject(object: Object?) {
if comments == nil || object == nil || object?.something == nil || object?.anything == nil {
return
}
self.objectsTableView.beginUpdates()
if self.objects!.count == 10 {
self.objects?.removeAtIndex(9)
self.objectsTableView.deleteRowsAtIndexPaths([NSIndexPath(forRow : 9, inSection: 0)], withRowAnimation: .Right)
}
self.objects?.insert(object!, atIndex: 0)
self.objectsTableView.insertRowsAtIndexPaths([NSIndexPath(forRow : 0, inSection: 0)], withRowAnimation: .Right)
self.objectsTableView.endUpdates()
}
But after some stress test, the log notify:
Invalid update: invalid number of rows in section 0. The number of
rows contained in an existing section after the update (1) must be
equal to the number of rows contained in that section before the
update (10), 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 don't know whats happening, this happens only when the insert of objects is very extreme, like one per 0.2 seconds.
Someone know that I can do?
Model mismatch
The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (10), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted)
In plain English for the reasonable man, the UITableView thinks you should have 11 rows:
10 before the update + 1 inserted.
number of rows contained in an existing section after the update (1)
...refers to numberOfRowsInSection is returning 1 for section 0, which indicates that the objects array is out of sync, assuming you use something like below:
override func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return objects.count
}
Use NSFetchedResultsController
A clean solution is to use NSFetchedResultsController to be the interface between your model and the UI. It has well studied boilerplate code and is a great platform to ensure thread safety. Documentation here.
Note:
Neat effect! The cell seems to rotate around to the top.
I could not break it using the Gist you produced, nor scheduling multiple concurrent tests. There must be a rogue access to your Object array.
Demo
This simplified version works. Just hook doPlusAction to a button action and watch it loop:
class TableViewController: UITableViewController {
var objects:[Int] = [0,1,2,3,4]
var insertions = 5
#IBAction func doPlusAction(sender: AnyObject) {
tableView.beginUpdates()
objects.removeAtIndex(4)
tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: .Right)
objects.insert(insertions++, atIndex: 0)
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .Right)
tableView.endUpdates()
let delay = 0.1 * Double(NSEC_PER_SEC) //happens the same with this too, when reach 100-150 items
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.doPlusAction(self)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
cell.textLabel!.text = "Cell \(objects[indexPath.row])"
return cell
}
}
Name of the guy that solved the problem: Semaphore
The error still happens, but only with a high size of items on list. I don't know what can be.
The DataSource protocol:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = self.objects?.count ?? 0
if self.semaphore != nil && semaphoreCode == BLOCKED_STATE {
dispatch_semaphore_signal(self.semaphore!)
}
return count
}
The method that add object:
func addObject(object: Object?) {
if object == nil {
return
}
if self.semaphore != nil {
let tempSemaCode = dispatch_semaphore_wait(semaphore!, 100000)
if tempSemaCode == BLOCKED_STATE {
self.semaphoreCode = RELEASED_STATE
}
}
if self.objects != nil && semaphoreCode != BLOCKED_STATE {
var needsRemoveLastItem = false
if self.objects!.count == 10 {
self.objects?.removeAtIndex(9)
needsRemoveLastItem = true
}
self.objects?.insert(object!, atIndex: 0)
if self.objects!.count > 0 {
self.objectsTableView.beginUpdates()
if needsRemoveLastItem {
self.objectsTableView.deleteRowsAtIndexPaths([NSIndexPath(forRow : 9, inSection: 0)], withRowAnimation: .Right)
}
self.objectsTableView.insertRowsAtIndexPaths([NSIndexPath(forRow : 0, inSection: 0)], withRowAnimation: .Right)
self.objectsTableView.endUpdates()
self.semaphore = dispatch_semaphore_create(BLOCKED_STATE)
}
}
}
I'm implementing AdMob in a UITableView by putting banner ad in the first row of a section. I'm most of the way there implementing it, however I'm having a tough time getting cellForRowAtIndexPath to work as desired.
This is what my numberOfRowsInSection looks like:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count = Int()
if let sections = fetchedResultsController.sections {
let currentSection = sections[section]
count = currentSection.numberOfObjects
count = count + 1 // add another row for an ad
}
return count
}
My cellForRowAtIndexPath looks like this:
override func tableView(tableView: UITableView, var cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let adCell: BannerAdTableViewCell = tableView.dequeueReusableCellWithIdentifier(BannerAdTableViewCell.reuseIdentifier(), forIndexPath: indexPath) as! BannerAdTableViewCell
// customization
return adCell
} else {
// Cell for vanilla item to display
// TODO: fix indexpath here. need to add 1
let newIndexPath = indexPath.indexPathByAddingIndex(indexPath.row+1)
indexPath = newIndexPath
// Cell for a Routine
let customCell = tableView.dequeueReusableCellWithIdentifier(RoutineSelectionTableViewCell.reuseIdentifier(), forIndexPath: indexPath) as! RoutineSelectionTableViewCell
let routine = fetchedResultsController.objectAtIndexPath(indexPath) as! SavedRoutines
customCell.routineNameLabel.text = routine.routineTitle
return customCell
}
}
I know I need to adjust the value of the indexPath to account for an extra row in the indexPathSection, but everything I've tried triggers out of bounds exceptions of some sort. Any feedback would be greatly appreciated.
indexPathByAddingIndex adds a new index, it does not increment a value of an index but adds one. If you previously had two indices / dimensions (section and row) you now have 3 indices / dimension: section, row and "the newly added one".
Provides an index path containing the indexes in the receiving index path and another index.
What you should do instead is either create a new NSIndexPath by hand. And I do not think you need to add one, but subtract one, since the item at index 1 should actually be the element in your result at index 0:
let customIndexPath = NSIndexPath(forRow: indexPath.row - 1, inSection: indexPath.section)
which you then use to access the "correct" routine at the right index:
let routine = fetchedResultsController.objectAtIndexPath(customIndexPath) as! SavedRoutines
Your call to tableView.dequeueReusableCellWithIdentifier should stay the same and still pass in the default indexPath.
I'm having trouble adding rows to the UITableView upon UIButton click.
I have two custom-cell xibs - one that contains an UILabel, another one that contains an UIButton.
Data for the table cell is loaded from two dictionaries (answersmain and linesmain).
Here is the code for the UITableView main functions:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.linesmain["Audi"]!.count + 1
}
// 3
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if(indexPath.row < 3){
var cell:TblCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! TblCell
cell.lblCarName.text = linesmain["Audi"]![indexPath.row]
return cell
} else {
var celle:vwAnswers = self.tableView.dequeueReusableCellWithIdentifier("cell2") as! vwAnswers
celle.Answer.setTitle(answersmain["Good car"]![0], forState:UIControlState.Normal)
return celle
}}
What do I put here?
#IBAction func option1(sender: UIButton) {
// I need to add rows to the uitableview from two dictionaries into two different xibs
}
You can do the next:
var showingAll = false
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return showingAll ? self.linesmain["Audi"]!.count + 1 : 0
}
#IBAction func option1(sender: UIButton) {
showingAll = true
tableView.beginUpdates()
let insertedIndexPathRange = 0..<self.linesmain["Audi"]!.count + 1
var insertedIndexPaths = insertedIndexPathRange.map { NSIndexPath(forRow: $0, inSection: 0) }
tableView.insertRowsAtIndexPaths(insertedIndexPaths, withRowAnimation: .Fade)
tableView.endUpdates()
}
You should take a look over the documentation here
There is this UITableView method called insertRowsAtIndexPaths:withRowAnimation: that inserts row at a specified indexPath.
You need to modify linesmain and answersmain by adding data to these and then call [self.tableView reloadData].
It would be better if you extract linesmain["Audi"] and answersmain["Good car"] and save them into different mutable arrays and modify those.
You need to do this in the func option1.