将目标添加到 UITableview 中的 UITextField (Swift)

Add Target to UITextField within a UITableview (Swift)

我想检查用户何时开始编辑文本字段。关于如何做到这一点有一个非常明确的答案

但是,在我的例子中,我的 textField 位于一个 UITableview 中,该 UITableview 被设置为它自己的 class。我已经尝试了很多不同的方法来让它工作,但我总是遇到崩溃 "libc++abi.dylib: terminating with uncaught exception of type NSException" 我在 textFieldDidChange 函数中设置了一个中断并且它从未被调用所以问题似乎出在我的调用方式上来自目标的功能。

class TextFieldCell: UITableViewCell {

    lazy var textField: UITextField = {
        let tf = UITextField()
        tf.translatesAutoresizingMaskIntoConstraints = false
        tf.textAlignment = .center
        tf.textColor = .black
        tf.font = UIFont.systemFont(ofSize: 17)
        tf.clearButtonMode = .whileEditing
        return tf
    }()

    // For simplicity, the rest of the Cell setup not shown.
    // Adds target in AirInput VC to fire method when editing happens

    textField.addTarget(self, action: #selector(AirInputViewController.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)

}


class AirInputViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

    @objc func textFieldDidChange(_ textField: UITextField) {

    }

}

我也为目标尝试了以下方法,但它也崩溃了。

textField.addTarget(AirInputViewController.self, action: #selector(AirInputViewController.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)

感觉好像我遗漏了一些简单的东西,但我不知道那个简单的修复是什么。或者我应该在 AirInputViewContoller 中添加目标吗?如果是这样,我将如何访问文本字段所在的 UITableViewCells?谢谢!

您的崩溃可能是因为您这样做了:

textField.addTarget(self, action: #selector(AirInputViewController.textFieldDidChange(_:)), for: UIControl.Event.editingChanged)

这里 selfTextFieldCell,所以我认为它试图去检查 AirInputViewControllerTextFieldCell 里面,但事实并非如此。

我会做:

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
    }
}

希望对您有所帮助。