首页 > 解决方案 > 如何访问swift 5中tableview单元格内的textview值?

问题描述

我有一个视图控制器,里面有一个表格视图和 2 个保存和取消按钮。在 tableview 单元格中,我有一个 textview。在 textview 中添加一些文本后,我想显示该文本。我不确定如何在单击保存按钮时获取该表格视图文本。(行数可能是动态的)。

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

                if let cell = tableview.dequeueReusableCell(withIdentifier: "SummaryManualEditContentCell", for: indexPath) as? SummaryManualEditTableCell {


                    cell.txtAnswers.text = "enter text here"

                    return cell
                }
            return UITableViewCell()
        }

@IBAction func btnSave(_ sender: Any) {
        print("textviewText1 + textviewText2 + and so on ")
   }

除了单击按钮之外,我还想将多个文本视图中的所有文本添加到一个字符串中。有没有什么干净和最好的方法来实现这一目标?

感谢您的帮助!

标签: iosswifttablecell

解决方案


您需要获取要获取其文本的单元格的 indexPath 以获取该 indexpath 的单元格,例如

@IBAction func btnSave(_ sender: Any) {
      let indexPath = IndexPath(row: 0, section: 0)
      if let cell = tableView.cellForRow(at: indexPath) as? SummaryManualEditTableCell {
        let text = cell.txtAnswers.text
        }
    }

如果您有多个带有 textFields 的单元格,您可以循环获取所有字段

  @IBAction func btnSave(_ sender: Any) {
var allTextViewsText = ""
       for i in 0...5{
          let indexPath = IndexPath(row: i, section: 0)
          if let cell = tableView.cellForRow(at: indexPath) as? SummaryManualEditTableCell {
            allTextViewsText += cell.txtAnswers.text
            }
        }
  print(allTextViewsText)
}

但请记住,这种方法仅适用于可见单元格,否则对于不可见单元格,您将得到 nil

我建议您在每个具有textViewtableView 的 viewController 委托的单元格中实现 textView:shouldChange。当单元格中的文本发生更改时,委托应将更改传播到视图控制器,视图控制器会将值保存在变量中。

然后,当您按下保存按钮时,您只需从变量中获取值。


推荐阅读