Reputation: 217
So I created this number of sections based on user input. For example I inputed 2 sections, I filled with 1 - 8 numbers, and it work just fine:
But when I inputed 4 sections and I filled with 1 - 16 numbers, but look at the section 1, the value changed I do not know why. Here's the pict:
Here my function code:
func getAllValue() {
for sectionIndex in 0...finalSectionNumber - 1 {
print("section index: \(sectionIndex)")
print("final txt field: \(finalSectionNumber)")
for rowIndex in 0...tableView.numberOfRows(inSection: sectionIndex) - 1 {
let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
let cells = tableView.cellForRow(at: indexPath) as? CellOutlet
print("row index: \(rowIndex)")
print(cells?.txtFieldSpecNumb.text ?? 0)
}
}
}
What did I miss here? Can anyone help?
Thankyou in advance
Upvotes: 1
Views: 600
Reputation: 160
Cells are reused, when you scroll and if visibility of cell goes out of screen area, then they are reused.
You must have to take temporary array to save values and make them in sync with cell indexes. Set those values in cellForRowAt Index path method from array you created.
Upvotes: 2
Reputation: 535944
Remember, cells are reused. A cell can jump from being in one row to being another row. But even more important: This approach is completely wrong:
let cells = tableView.cellForRow(at: indexPath) as? CellOutlet
print("row index: \(rowIndex)")
print(cells?.txtFieldSpecNumb.text ?? 0)
Never never never (did I mention "never"?) treat view as model. The cells, the text field, are not the data. If you want to know what the data is, look in the data. Consult the data model, not the table view. (Of course you have been keeping everything the user types in the text fields in your data model, haven't you?)
Upvotes: 3