ios - 将引用存储在变量 SWIFT 4 中

标签 ios swift swift4 inout

我将一个参数从我的 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/

相关文章:

ios - RxSwift,如何在不使用 RxDataSourced 的情况下绘制 tableView?

ios - UITableViewCell 及其 socket 是否在 `dequeueReusableCellWithIdentifier` 之后初始化?

ios - 如何增加 MDCTextInputControllerOutlinedTextArea 的高度

ios - 如何测试 UIAlertController 的完成处理程序中调用的方法?

ios - 如何在 UIScrollView 中分页时一次仅加载一个 ViewController

ios - 动画重复时更改 View 的颜色

ios - 如何在 Swift 4.0 中以编程方式调用 GestureRecognizer 方法?

Swift 4 可解码 : How to map multiple values to a single enum value?

iphone - 我怎样才能等待进程树完成?

objective-c - 调用 hide 后 MBProgressHUD 没有消失