如何快速在文本字段中保存文本?

问题描述 投票:0回答:1

我有一个由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)

    }
ios uitextfield swift4
1个回答
0
投票

似乎您有一个独立变量queryTextField,在创建第二个单元格时将其覆盖。

此外,在textFieldDidEndEditing中尝试访问textField而不是queryTextField,如下所示:

func textFieldDidEndEditing(_ textField: UITextField) {
     var temp = textField.text!
     queryArray.append(temp)

     print(temp)
}

对此回应:

我需要每个单元格都有其文本字段,并且我需要能够保存他们的文本排列成一个数组。之后,我将其发送到网络服务。总结起来,它们将是我的参数。

  1. 您不必为此仅拥有全局queryTextField。如果这是唯一的目标,则可以删除此变量。
  2. 您是否需要在某个触发器上发送网络请求?点赞按钮。我想是的。
  3. 由于从理论上讲,并非所有单元格都能同时显示(例如,当提示框不适合屏幕时),因此尝试在文本字段中跟踪文本是个坏主意。相反,您需要某种模型来存储所有文本(可能与indees配对)。最简单的是字典,其中key是单元格标识符(例如indexPath),value是文本。
  4. textFieldDidEndEditing中,您可以将更改报告给视图控制器。为此,您需要将单元格分配为其文本字段的委托。并查看控制器-作为单元的委托。在textFieldDidEndEditing单元格中,将调用视图控制器委托方法来报告文本更改,并传递(例如)自身和文本作为参数。然后,视图控制器将能够找到其索引路径并将文本存储在模型中(字典)。
  5. 在触发(单击按钮?)时,视图控制器将能够从模型(词典)构建参数。

将此伪代码视为方向:

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
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.