[英]Swift Pass/Save Text From TextView Inside CustomCell & Make The Text Not Disappear After Cell Resuse
我很难找到或想到一种可以存储 textView 文本的方法。 所以以后如果需要我可以将它传回服务器。
我在 CustomCell UITableViewCell 中有一个 TextView。 (我的表格视图中有 2 个部分,在每个部分中都有一个自定义单元格,里面有一个 textView。)我需要以某种方式传递或保存用户编写的文本,以便我可以提取该文本并将其发送到其他地方..每次我的“可重复使用”单元格中的文本被重复使用时,文本就会消失。 我试图将它保存在我的 customCell Swift 中,但我认为将文本保存在 customCell 文件中并不是一个好主意。 有人知道吗? 谢谢你!
在实现 tableView 时,我们应该确保有一些数据驱动的数据源。 我的意思是创建一个 model 来驱动 tableView 的 numberOfSections、numberOfRowsInSection 等。这样你就可以在 model 中拥有一个属性来存储 textView 的文本。
样品 Model:
struct TableViewModel {
// this will handle number of sections
var sections: [TableViewSectionModel]
}
struct TableViewSectionModel {
// this will handle number of rows
var rows: [TableViewRowModel]
}
struct TableViewRowModel {
var textViewText: String
/*
Other properties to fill in
*/
}
使用它,您可以像这样创建数据模型:
var cell1 = TableViewRowModel(textViewText: "")
var cell2 = TableViewRowModel(textViewText: "")
var section1 = TableViewSectionModel(rows: [cell1, cell2])
var section2 = TableViewSectionModel(rows: [cell1, cell2])
var data = TableViewModel(sections: [section1, section2])
这将有助于更新 model 中的属性,您可以稍后将数据传递到后端。
第一步:创建一个 model 来填充单元格。
struct myModel {
let textFromCustomCell: string = ""
}
创建模型列表(以填充表格视图)
第二步:这有几种方法可以做到,但我选择了委托方法。
使您的 CustomCell 符合 UITextViewDelegate。
在 CustomCell 上保存一个 indexPath 变量:
var indexPath: 索引路径?
在单元格上实现此 UITextview 委托方法:
func textViewDidChange(textView: UITextView)
在单元 awakeFromNib 中设置 textView 代表:
override func awakeFromNib() { super.awakeFromNib() textField.delegate = self
}
5.创建一个CustomCellDelegate:
protocol CustomCellDelegate: AnyObject {
func cellTextDidChanges(indexPath: IndexPath, text: String)
}
需要时在单元格上调用此 function(可能在单元格上的 textViewDidChange function 实现中)。
使包含 tableview 的 viewController 符合您的 CustomCellDelegate
在 viewController 上实现 CustomCellDelegate cellTextDidChanges 方法
在 cellTextDidChanges 实现中,您应该根据 indexPath 在您创建的 model 列表上更新正确的 model 文本。
请记住,第一次填充表格视图时,文本将为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.