Reputation: 61
I am creating a custom subclass from UITextField class. I want to apply something while textfield is focused. But in my custom class my delegate methods are not calling.
I have create a subclass that extends UITextField class and make some customisation.
In TGTextField class:
class TGTextField: UITextField, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
delegate = self
createBorder()
}
required override init(frame: CGRect) {
super.init(frame: frame)
delegate = self
createBorder()
}
func createBorder(){
self.layer.borderColor = AppColor.TextFieldColors.BorderNormalColor.cgColor
self.layer.borderWidth = 1.0;
self.layer.cornerRadius = 8
}
func textFieldDidBeginEditing(textField: UITextField) {
print("focused")
self.activeTextFieldColor()
}
func textFieldDidEndEditing(textField: UITextField) {
print("lost focus")
self.deactiveTextFieldColor()
}
func activeTextFieldColor(){
self.layer.borderColor = AppColor.TextFieldColors.BorderActiveColor.cgColor
}
func deactiveTextFieldColor(){
self.layer.borderColor = AppColor.TextFieldColors.BorderNormalColor.cgColor
}
}
Both these delegates methods are not called.
func textFieldDidBeginEditing(textField: UITextField) {
print("focused")
self.activeTextFieldColor()
}
func textFieldDidEndEditing(textField: UITextField) {
print("lost focus")
self.deactiveTextFieldColor()
}
Upvotes: 1
Views: 2530
Reputation: 15748
Your code works for me. These delegate methods in the custom class won't be called if you set text field delegate to the corresponding view controller after you've initialized the text fields.
To avoid this add target in TGTextField
instead of UITextFieldDelegate
class TGTextField: UITextField {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
//delegate = self
createBorder()
}
required override init(frame: CGRect) {
super.init(frame: frame)
//delegate = self
createBorder()
}
func createBorder(){
self.layer.borderColor = UIColor.red.cgColor
self.layer.borderWidth = 1.0;
self.layer.cornerRadius = 8
addTarget(self, action: #selector(activeTextFieldColor), for: .editingDidBegin)
addTarget(self, action: #selector(deactiveTextFieldColor), for: .editingDidEnd)
}
@objc func activeTextFieldColor(){
self.layer.borderColor = UIColor.green.cgColor
}
@objc func deactiveTextFieldColor(){
self.layer.borderColor = UIColor.red.cgColor
}
}
Upvotes: 4
Reputation: 4226
Looks like you're implementing the wrong method signature; you should put _
before textField
, like this
func textFieldDidBeginEditing(_ textField: UITextField) {}
func textFieldDidEndEditing(_ textField: UITextField) {}
Xcode should help you highlighting with a warning
Instance method 'textFieldDidBeginEditing(textField:)' nearly matches optional requirement 'textFieldDidBeginEditing' of protocol 'UITextFieldDelegate'
Upvotes: 1