我将一个参数从我的 viewController 发送到 customCell。我的自定义单元格有一个文本字段。在我的 viewController 中,我有一个字符串变量用于将值存储在 textField 中,因为我将把这个值发送到其他服务。
我的自定义单元格
customCell: TableViewCell: {
var data: String?
@IBOutlet weak var textField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
}
func setData(data: inout String) {
self.data = data
}
}
extension customCell: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
data = textField.text ?? ""
}
}
我的 View Controller
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customCell
cell.setData(data: &data.email)
return cell
}
当我将引用发送到 customCell 时,我在 textFieldDidEndEditing 方法中丢失了引用。
最佳答案
不要那样做。
使用类
创建数据模型。一个类是引用类型
class Model {
var name : String
var email : String
init(name: String, email: String) {
self.name = name
self.email = email
}
}
声明数据源数组
var models = [Model]()
在单元格中声明模型的属性(顺便说一下,类名以大写字母开头)
class CustomCell: TableViewCell {
@IBOutlet weak var textField: UITextField!
var model: Model! {
didSet {
textField.text = model.email
}
}
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
}
}
extension CustomCell: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
model.email = textField.text ?? ""
}
}
在 cellForRow 中将模型传递给单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
cell.model = models[indexPath.row]
return cell
}
由于引用语义,模型中的值得以保留。
关于ios - 将引用存储在变量 SWIFT 4 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49656660/