我无法在动态 table 视图 swift 中获取文本字段值
I could not get text field value in dynamic table view swift
所以我根据用户输入创建了这个数量的部分。
例如我输入了 2 个部分,我填入了 1 - 8 个数字,它工作得很好:
但是当我输入4个section的时候填入1-16个数字,但是看第1个section,不知道为什么数值变了。这是图片:
这里是我的函数代码:
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)
}
}
}
我错过了什么?
有人可以帮忙吗?
提前致谢
请记住,单元格被重复使用。一个单元格可以从一行跳到另一行。但更重要的是:这种做法是完全错误的:
let cells = tableView.cellForRow(at: indexPath) as? CellOutlet
print("row index: \(rowIndex)")
print(cells?.txtFieldSpecNumb.text ?? 0)
Never never never(我有提到“从不”吗?)将 view 视为 model。单元格、文本字段不是数据。如果您想知道数据是什么,查看数据。请查阅数据模型,而不是 table 视图。 (当然,您一直将用户在文本字段中键入的所有内容保留在您的数据模型中,不是吗?)
单元格被重用,当您滚动并且单元格的可见性超出屏幕区域时,它们将被重用。
您必须使用临时数组来保存值并使它们与单元格索引同步。在您创建的数组的 cellForRowAt Index 路径方法中设置这些值。
所以我根据用户输入创建了这个数量的部分。 例如我输入了 2 个部分,我填入了 1 - 8 个数字,它工作得很好:
但是当我输入4个section的时候填入1-16个数字,但是看第1个section,不知道为什么数值变了。这是图片:
这里是我的函数代码:
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)
}
}
}
我错过了什么? 有人可以帮忙吗?
提前致谢
请记住,单元格被重复使用。一个单元格可以从一行跳到另一行。但更重要的是:这种做法是完全错误的:
let cells = tableView.cellForRow(at: indexPath) as? CellOutlet
print("row index: \(rowIndex)")
print(cells?.txtFieldSpecNumb.text ?? 0)
Never never never(我有提到“从不”吗?)将 view 视为 model。单元格、文本字段不是数据。如果您想知道数据是什么,查看数据。请查阅数据模型,而不是 table 视图。 (当然,您一直将用户在文本字段中键入的所有内容保留在您的数据模型中,不是吗?)
单元格被重用,当您滚动并且单元格的可见性超出屏幕区域时,它们将被重用。
您必须使用临时数组来保存值并使它们与单元格索引同步。在您创建的数组的 cellForRowAt Index 路径方法中设置这些值。