Rob
Rob

Reputation: 47

Calling delegate methods in custom UITextField class

So this might be basic Swift knowledge but I'm struggling to find this info anywhere online. I'm trying to create a custom text field glass with global styles that utilizes UITextFieldDelegate methods. In particular I'm trying to use the function textFieldDidBeginEditing(). In my example below I'm just trying to print "hello" when a text field is being edited, however nothing is being printed to the console when I begin typing in my custom text field.

If I'm doing anything incorrectly please let me know, as I don't work with Swift too much. Thank you!

class LoFMTextField: UITextField {

    override init(frame: CGRect) {
        super.init(frame: frame)
        styleTextField()
    }

    required init?(coder LoFMDecoder: NSCoder) {
        super.init(coder: LoFMDecoder)
        styleTextField()
    }

    func styleTextField() {
        layer.cornerRadius = 5.0
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.white.cgColor
        backgroundColor = UIColor.white
    }

}

extension UITextFieldDelegate {

    func textFieldDidBeginEditing(textField: UITextField!) {
        print("hello")
    }

}

Upvotes: 1

Views: 251

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Add this line inside styleTextField

self.delegate = self 

Then

extension LoFMTextField : UITextFieldDelegate { 
   func textFieldDidBeginEditing(_ textField: UITextField) {
      print("hello")
   }
}

Note: it's (_ textField: UITextField) not (textField: UITextField!)

Upvotes: 2

Related Questions