ios - 如何访问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 ")
}
除了单击按钮之外,我还想将多个文本视图中的所有文本添加到一个字符串中。有没有什么干净和最好的方法来实现这一目标?
感谢您的帮助!
解决方案
您需要获取要获取其文本的单元格的 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
我建议您在每个具有textView
tableView 的 viewController 委托的单元格中实现 textView:shouldChange。当单元格中的文本发生更改时,委托应将更改传播到视图控制器,视图控制器会将值保存在变量中。
然后,当您按下保存按钮时,您只需从变量中获取值。
推荐阅读
- charts - 如何在 Apex 图表中同时使用渐变和单色?
- python - 如何向现有字典添加新键并将前一个键作为值附加到在 for 循环中创建的新键:python
- regex - 如何在 google 表格中解析此 URL 以仅显示价格?
- flutter - 像在android启动器中一样在flutter中创建一个文件夹
- swiftui - 如何在 SwiftUI 中隐藏从子视图中的 tabItem 导航的 TabView?
- sql - 在 bigquery 中将罗马数字转换为阿拉伯数字的最佳方法是什么?
- machine-learning - 为什么网络架构的差异会导致名称分类的巨大差异
- c - 在 C 中将 extern 与多维数组一起使用
- android - 使用生产密钥 Stripe 反应原生应用程序崩溃
- spring-boot - 如何使 Spring Boot 2 Bouncy Castle FIPS 兼容?