首页 > 解决方案 > 我应该如何将文本设置到 tableview 上的文本字段中?

问题描述

我有这个问题,我有一个带有自定义单元格的表格视图,自定义单元格有一个文本字段,我应该使用自定义按钮将文本放在这个文本字段中,按钮不在表格视图中。我的问题是,如何将文本设置为文本字段?我的另一个问题是我无法识别设置文本的当前文本字段,我只知道标签。

这是我的代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! budgetCellTableViewCell
  cell.insertText.delegate = self
  cell.insertText.tag = indexPath.row
  cell.insertText.inputView = UIView()
  cell.showViews()
  if let money = arrayData[indexPath.row]["amount"]
  {
        cell.showSubtitle.text = "Ultimos 30 dias: \(money)"
  }
  if let cat = arrayData[indexPath.row]["category"]
  {
        cell.showTitle.text = cat as? String
  }
  cell.selectionStyle = .none
  return cell
}

func textFieldDidBeginEditing(_ textField: UITextField) {


    if self.textFieldTagActive == textField.tag
    {
        textField.text = setText
    }
    else
    {
        self.setText = ""
        self.textFieldTagActive = textField.tag
    }


func addNumber(_ number: Int) {

    if number != -1
    {
        setText += String(number)
    }
    else
    {
        setText.removeLast()
    }
}

当我使用函数 textFieldDidBeginEditing 按下我的自定义按钮时使用函数 addNumber 我得到文本字段标签,我按下我的自定义按钮,最后我按下相同的文本字段并且文本出现在文本字段中,但我真的想按下我的按钮和同时,文本出现在文本字段中

那么,由于我的自定义按钮不在表格视图中,如何将文本设置到我的文本字段中?

谢谢

标签: swiftdelegatestableviewtextfield

解决方案


您可以从委托函数中获取当前文本字段。

class ViewController: UIViewController {

    var currentText = "your text"
    var currentTF: UITextField?

    @IBAction func buttonTapped(_ sender: Any) {
        // set text to the text field.
        currentTF?.text = currentText
    }

}

extension ViewController: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        // get the text field that you want
        currentTF = textField
        return true
    }
}

推荐阅读