How do I add numbers to each tableview row beginning from 1 - swift

I have created a TableView with a Prototype Cell with a lot of content in it, multiple labels, 2 pictures and a view which is colored if the row is selected.
What I want to do now, is I want to add a number for each of the rows created so the user can see how many rows there are. I can't use the ID I get from the Database since it is a random mix of characters.
I added an Int variable 'participantID' which starts from one and increments by one with every cell created and writes the value in a label within the prototype cell.
This does exactly what I want, with just one issue: Every time i scroll in the table the ID is incremented. I know that's because of the reuse of the cells however I couldn't find a way to fix this issue.
This is how it looks (particID):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tbcCourseParticipant", for: indexPath) as! participantCell
let partic = participants[indexPath.row]
cell.lblId?.text = String(particID)
cell.lblName?.text = partic.name
cell.lblFirstName?.text = partic.firstName
cell.lblBirthDate?.text = partic.birthDate
cell.lblPhoneNr?.text = partic.phoneNr
cell.lblPrice?.text = String(partic.payed) + "€"
particID += 1
return(cell)
}

The total number of rows is participants.count. The number of this row is indexPath.row+1 (I add 1 because the user will not expect to start counting at zero the way a programmer would do).
So I would say:
cell.lblId?.text = String(indexPath.row+1)
Or maybe:
cell.lblId?.text = String(indexPath.row+1) + " of " + String(participants.count)

Related

How to print index number on tableview cell?

I want to print the number of the tableview cell based on the number of tableview cells that are there so if there are 15 cells. The first cell should be 1 and the 15th should state 15. I want this printed before a fetch that is already being printed. I posted a picture of what I am looking for below.
cell.textLabel?.text = [" Course: ",attr1," : ", attr2].flatMap { $0 }.reduce("", +)
You can try:
let text = [" Course: ",attr1," : ", attr2].flatMap { $0 }.reduce("", +)
cell.textLabel?.text = "\(indexPath.row+1) \(text)"
Hope this helps.

Swift - My collection view is not outputting an extra amount

The count of chosenPlanArray.count is 5 here, and that is how many cells my collection view ends up having.
However, when i try an append values from the collection view to arrays, my collection view is iterating over itself an extra amount of times - in this example it gets to 9 iterations. Even though 'return chosenPlayArray.count' is 5. This is very random and ive been playing with my code all day trying to fix it. Has this ever happened to anybody ?
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return chosenPlanArray.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! CustomPlanItCollectionViewCell
cell.planImage.downloadedFrom(link: chosenPlanArray[indexPath.item].imageForPlan!)
cell.planLbl.text = chosenPlanArray[indexPath.item].nameOfEvent
cell.dateTimeLbl.text = chosenPlanArray[indexPath.item].eventStartsAt
if cell.dateTimeLbl.text == nil {
datesForFirebase = [""]
} else {
datesForFirebase.append(cell.dateTimeLbl.text!)
}
individualPlanNames.append(cell.planLbl.text!)
imagesOfPlan.append(chosenPlanArray[indexPath.row].imageForPlan!)
print(chosenPlanArray.count)
print(imagesOfPlan.count)
print(nameOfEventPlan.count)
print(individualPlanNames.count)
return cell
}
Here is my output for those print statements at the bottom. Notice how the first print statment is correct - the actual size of the collection view is 5, as you can tell by the numberOfitems in sec.. I find it weird how the other print statements start at 1, and then loop past the size of 'chosenPlanArray.count' - Is the issue the way i may be appending the values to my arrays? This is causing me to get the wrong number of values uploaded to my firebase. So i need to figure this tricky situation out. Thanks
5 // first print statement print(chosenPlanArray.count)
1 // second print statement print(imagesOfPlan.count)
1 // fourth print(nameOfEventPlan.count)
1 // third print(individualPlanNames.count)
5
2
2
2
5
3
3
3
5
4
4
4
5
5
5
5
5
6
6
6
5
7
7
7
5
8
8
8
5
9
9
9
You have to know that there is cell reusing , which means every scroll a call to cellForItemAt happens which means these lines run again
individualPlanNames.append(cell.planLbl.text!)
imagesOfPlan.append(chosenPlanArray[indexPath.row].imageForPlan!)
and the size of their content increases

Section index in tableview without section (Swift)

Question 1: How can i have section index in tableview without section?
Question 2: Could i have those section index for specific rows in a table? For example: i want the section index to be implemented whenever indexpath.row > 4.
Table views in UIKit always have sections and rows. By saying you don't want a section, you are really saying that you simply want only one section (at section index 0) that holds all rows (with indexes relative to section index 0).
Note: You can easily have a section without a section header in which case the user will never know that all rows are actually contained in a section.
When you implement your table view data source, you will want to implement numberOfSections and numberOfRowsInSection in order to let the table view know how many sections and rows you want.
See UITableView.
I think you mean with only one single section (you can't have no sections). Here's how I do this:
Create index titles that are just string versions of the array indexes. If there are too many to fit on the screen, iOS will skip some and replace them with bullets to make it clear that there are some indexes not being displayed. You will be guaranteed that the index range is the same as your row range. (Unless you have zero rows).
Instead of returning the section index, return -1. This will do nothing. Programatically scroll to the ROW of the passed in index.
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if myDataSourceArray.count > 0 {
return Array(1...myDataSourceArray.count).map({String($0)}).map({ String($0) })
}
return []
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
tableView.scrollToRow(at: IndexPath(row: index, section: 0), at: .middle, animated: true)
return -1
}
(I actually set my minimum count to 20, rather than zero, as there's not much point in having an index when all items in the table are on the screen. But you do need to check for at least greater than zero, otherwise it will try to create an index of "1" for a table with no rows, and this will cause a crash.)
You may want different index titles other than just numbers, but hopefully this gives you some idea on how it can be done. Once you have a different number of indexes to what you have rows, you would have to come up with some other more complicated way of relating index numbers or index titles to row numbers.
Question1:To have section index in tableview without section, you can make height of section to 0.
Question2: If indexPath.row>4, get section index as: yourArray[indexPath.section]

Having trouble with sections in UITableView

I have the following code in my search method that updates the tableview.
for (int x = 0; x < [array count]; x++) {
//network stuff here
self.searchedReservations = [aSearchObjectType objectsFromServerDictionaries:aResultsArray];
[self.aTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}
Each object in the array represent a section in my table, for most cases the count will be 4, so 4 sections.
Right now, the code is loading the same data for all sections in the table's cells. Instead of the unique data for each section of the table.
Here is the code that loads the cells. I'm missing some logic that maps the data to the right section of the table.
MyClass *object = [self.searchedReservations objectAtIndex:iIndexPath.row];
cell.textLabel.text = object.customerFullName;
I assume you have the code below in your 'cellForRowAtIndexPath' method:
MyClass *object = [self.searchedReservations objectAtIndex:iIndexPath.row];
cell.textLabel.text = object.customerFullName;
Tables are organised into sections, then within each section there are rows. The rows start at zero again for each section.
If you are on section 0, loading cell 0 this code above is not taking the section number into account, only the row number - so it is loading:
[self.searchedReservations objectAtIndex:0]
to populate the cell.
When you are on section 1, loading cell 0 in section one, you are retrieving exactly the same value because you are just using the row number. ie. you're still loading
[self.searchedReservations objectAtIndex:0]
You may think that you are changing the value of the 'searchedReservations' object between the loading of each section (this is what it looks like you're trying to do in the loop above) but I'm not sure that this is working (as the code the populate searchedReservation doesn't seem to do anything different in each loop counter). Also the first time the table loads it will run through all of the rows in all of the sections anyway.
I think you need to either use the indexPath.section field as well as the indexPath.row field at the time you are populating the cell to ensure you are setting the appropriate row in the appropriate section.
Also use the debugger to see whats going on in your cellForRowAtIndexPath method and in your loop and make sure that you are getting/using a different 'searchedReservations' object for each incrementation of the loop and that this matches the 'searchedReservations' object in the cellForRowAtIndexPath method.

Assign a single array value to different sections in iPhone

I have a array (resultArray) which has 21 items of data in it. I want to display it in a 8 sectioned table with different row counts.
How to assign the value properly in all row? Both indexpath.row and section.row gives wrong values. How to assign a single array value to grouped table with more section?
It's up to you to map your data model to the table view, and you can do it any way that you want. If you have a flat array of items and want to map them into different sections of the table view, you'll have to know which offsets of the result data go into which sections of the table, but no one can do that for you automatically, because only you know the semantics of the data. You need some code that takes the section and row index and figures out which index into the results array needs to be returned.
If it's always 21 items and always the same mapping, then hardcoding the mapping in a table or a big bunch of if statements is probably fine. If it's dynamic then you'd need some other lookaside mapping table, depending on how you wanted to map.
Finally, as #iPortable suggests, you could also find a way to structure your results data appropriately, which makes the controller logic simple, depending on your data.
I would create a multi layer array for this. The first level would be the section count and the second level the row. The array would look something like this:
resultArray{
1 = {
1 = first row in first section,
2 = second row in first section
},
2 = {
1 = first row in second section,
2 = second row in second section
}
}
then you get the value from the array in your cellForRowAtIndexPath: as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *sectionArray = [returnArray objectAtIndex:indexPath.section];
cell = [sectionArray objectAtIndex:indexPath.row];
}