【问题标题】:How do I gain access to a custom UITableViewCell from textFieldDidEndEditing?如何从 textFieldDidEndEditing 访问自定义 UITableViewCell?
【发布时间】:2019-06-22 09:12:19
【问题描述】:

我有一个自定义的UITableViewCell,我在其中添加了一个UITextField,我想对文本字段进行一些验证,并在单元格上设置一个hasError 属性,以便为单元格添加一个错误标签并更改文本字段的背景颜色。

我没有使用情节提要并以编程方式创建我的自定义单元格/UITableViewCell

我在我的UIViewController 中使用textFieldDidEndEditing 来检测文本更改并且无法访问单元格,以设置我的hasError 属性。

我想我可以通过标签循环视图/文本字段以字段文本字段然后获得它的父级。

或者我应该实现我自己的textFieldDidEndEditing 版本,然后触发另一个以单元格和文本字段为参数的事件。

但我不确定这是否是最好的方法或如何触发事件。

【问题讨论】:

  • 如果您在自定义单元格中添加textField,那么为什么不在自定义单元格中实现textFieldDidEndEditing

标签: ios swift uitableview cocoa-touch


【解决方案1】:

您可以使用Protocolhttps://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/Protocol.html

一个简单的例子:

cellForRow

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ....
    cell.delegate = self
    return cell
}

你的UITableViewCell 子类:

class Cell: UITableViewCell, UITextFieldDelegate {

    // MARK: - Properties

    weak var delegate: CellDelegate?
    ....

    // MARK: - Functions

    func textFieldDidEndEditing(_ textField: UITextField) {
        self.delegate?.cell(self, textFieldDidEndDiting: textField)
    }
}

您的协议

protocol CellDelegate: class {
    func cell(_ cell: Cell, textFieldDidEndDiting textField: UITextField)
}

最后,使你的控制器符合该协议,如下所示:

class ViewController: UIViewController, CellDelegate {

    func cell(_ cell: Cell, textFieldDidEndDiting textField: UITextField) {

    }

}

【讨论】:

  • 仍然没有在 viewController 中调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 2016-02-03
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多