Consider this:
class ViewController: UIViewController, UITextFieldDelegate {
var textfield: UITextField = {
let tf = UITextField(frame: CGRect(x: 0, y: 0, width: 140, height: 30))
}()
override func viewDidLoad() {
textfield.delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
print("Inside textfield")
}
}
When I tap inside the textfield, textFieldDidBeginEditing()
is called because the delegate handles that.
What happens if I want to subclass UITextField? How do I handle a tap event inside the subclassed textfield within the subclass? So for example:
class MyTextField: UITextField, UITextFieldDelegate {
required override init(frame: CGRect) {
self.delegate = self // CAN'T DO THIS!!!
}
func textFieldDidBeginEditing(_ textField: UITextField) {
print("Inside subclassed textfield")
// This function is NOT executed when I tap inside this subclassed textfield!!
}
}
The textFieldDidBeginEditing()
within the subclass never gets called, I guess because the delegate is not properly set, and I don't know how to set it. It's not possible to do: self.delegate = self
Do I need to create a protocol for MyTextField? If so, how do I hook it all up? What would the code using MyTextField have to do? If I do:
var subTF = MyTextField(....)
subTF.delegate = self
Is that .delegate for class UITextField?? or is it for the subclass MyTextField?