我有一个由2个单元格组成的表格视图,每个单元格都有一个文本字段。我想将文本字段中的文本保存在另一个变量中,并将其附加到数组中,但它只是将第二个单元格的文本字段的文本保存到变量中,而不附加数组。
这里是cellForRowAt代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == queryTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: queryCellReuseIdentifier,
for: indexPath) as! queryCell
cell.selectionStyle = UITableViewCell.SelectionStyle.gray
queryTextField = UITextField(frame: CGRect(x: 20, y: 0, width: 300, height: 20))
queryTextField.delegate = self
queryTextField.placeholder = "Soruyu buraya giriniz"
queryTextField.font = UIFont.systemFont(ofSize: 15)
cell.addSubview(queryTextField)
return cell
}
这是我的相关功能:
func textFieldDidEndEditing(_ textField: UITextField) {
var temp = queryTextField.text!
queryArray.append(temp)
print(temp)
}
似乎您有一个独立变量queryTextField
,在创建第二个单元格时将其覆盖。
此外,在textFieldDidEndEditing
中尝试访问textField
而不是queryTextField
,如下所示:
func textFieldDidEndEditing(_ textField: UITextField) {
var temp = textField.text!
queryArray.append(temp)
print(temp)
}
对此回应:
我需要每个单元格都有其文本字段,并且我需要能够保存他们的文本排列成一个数组。之后,我将其发送到网络服务。总结起来,它们将是我的参数。
queryTextField
。如果这是唯一的目标,则可以删除此变量。indexPath
),value是文本。textFieldDidEndEditing
中,您可以将更改报告给视图控制器。为此,您需要将单元格分配为其文本字段的委托。并查看控制器-作为单元的委托。在textFieldDidEndEditing
单元格中,将调用视图控制器委托方法来报告文本更改,并传递(例如)自身和文本作为参数。然后,视图控制器将能够找到其索引路径并将文本存储在模型中(字典)。将此伪代码视为方向:
cellForRow {
...
cell = ...
let textField = ...
textField.delegate = cell
cell.addSubview(textField)
cell.delegate = self
}
在单元格:
textFieldDidEndEditing(textField: UITextField) {
delegate?.report(text: textField.text ?? "", in: self)
}
在视图控制器中:
report(text: String, in cell: UITableViewCell) {
let indexPath = tableView.indexPath(of: cell)
model[indexPath] = text
}