Simply duplicate UITextFieldDelegate
with a new protocol and pass the calls from UITextFieldDelegate
through the custom delegate to the view controller.
First, create a new protocol with whichever delegate methods you want to pass through to the view controller.
protocol CustomTextFieldDelegate {
func textFieldDidChangeSelection(_ textField: UITextField)
}
Then, set the delegate of the subclass to self
, and whenever those methods are called (within the subclass), do what you need with them and then pass them along to the custom delegate.
class CustomTextField: UITextField {
var customDelegate: CustomTextFieldDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
delegate = self
}
required init?(coder: NSCoder) {
return nil
}
}
extension CustomTextField: UITextFieldDelegate {
func textFieldDidChangeSelection(_ textField: UITextField) {
// Do what you need in the subclass.
// When done, pass the call along to the custom delegate.
customDelegate?.textFieldDidChangeSelection(textField)
}
}
And the view controller will be able to use the delegate as if this pass-through wasn't there.
class SomeViewController: UIViewController {
let someTextField = CustomTextField()
override func viewDidLoad() {
super.viewDidLoad()
someTextField.customDelegate = self
}
}
extension SomeViewController: CustomTextFieldDelegate {
func textFieldDidChangeSelection(_ textField: UITextField) {
// Do work
}
}