可能是你的崩溃是由于你这样做:
textField.addTarget(self, action: #selector(AirInputViewController.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
这里 self 是 TextFieldCell ,所以我认为它试图去检查一下 AirInputViewController 在里面 TextFieldCell ,情况并非如此。
self
TextFieldCell
AirInputViewController
我会做:
class TextFieldCell: UITableViewCell { weak var delegate: TextFieldCellDelegate? lazy var textField: UITextField = { // same you have }() textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControl.Event.editingChanged) @objc func textFieldDidChange(_ textField: UITextField) { delegate?.textFieldDidChange(textField) }
创建一个花哨的委托:
protocol TextFieldCellDelegate: class { func textFieldDidChange(_ textField: UITextField) } class AirInputViewController: TextFieldCellDelegate { func textFieldDidChange(_ textField: UITextField) { // textField just changed! } // IMPORTANT! Set the delegate for the cell! func tableView(...cellForRow...) { let cell = ... as! TextFieldCell cell.delegate = self ... return cell } }
希望有所帮助。