如何为其编辑的内容提供自定义UITableViewCell上下文?

时间:2016-06-04 15:11:03

标签: ios swift

现在我有一个自定义UITableViewCell,其中包含UITextField。单元格时UITextField未启用用户交互。当您点击单元格时,textField将启用用户交互,然后成为第一响应者。 UITextFieldDelegate在自定义UITableViewCell类中实现。我的视图控制器有一个todos存储,我希望自定义UITableViewCell知道它正在编辑哪个待办事项,然后更新模型并在调用委托方法时完成编辑时查看。我该如何实现呢?

1 个答案:

答案 0 :(得分:3)

UITableViewCell的班级文件中,您可以声明如下协议:

protocol TextFieldUpdateDelegate {
    func textFieldHasChanged(textField: UITextField)
}

然后给你UITableViewCell类一个实例变量:

var textFieldUpdateDelegate: TextFieldUpdateDelegate?

当您处理UITextFieldDelegate方法时,您可能需要回调代理类似于:

    if (textFieldUpdateDelegate != nil) {
        textFieldUpdateDelegate!.textFieldHasChanged(textField)
    }

您的表视图控制器需要执行以下操作:

// declare that it implements the protocol
class YourTableViewController: UITableViewController: TextFieldUpdateDelegate


// Actually implement the method
func textFieldHasChanged(textField: UITextField) {
   // Do your magic
}

// Make sure to set the delegate on your table view cells
let cell = self.tableView.dequeueReusableCellWithIdentifier("YourCell") as! YourTableViewCell
cell.textFieldUpdateDelegate = self

希望这足以帮助您将所有部分连接起来。