Drew LeSueur Drew LeSueur -4 years ago 64
iOS Question

Swift: Why aren't my UITextFieldDelegate methods being called?

I am trying to programmatically create a

and create a delegate to handle the events. I am able to create add and the
just fine, but none of the
methods are bing added.
Why would this be?

let myTextField = UITextField()
myTextField.frame = CGRect(x:0, y: 100, width: 300, height: 30)
myTextField.text = "Example Text"

class MyTextFieldDelegate : NSObject, UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
print("should return!\n")
return true

func textFieldDidEndEditing(_ textField: UITextField) {
print(textField.text! + "\n")

func textFieldDidBeginEditing(_ textField: UITextField) {
print("yay begin!\n")
print(textField.text! + "\n")


let myTextFieldDelegate = MyTextFieldDelegate()
myTextField.delegate = myTextFieldDelegate

Answer Source

In UITextField, delegate is declared as a weak property.

weak var delegate: UITextFieldDelegate? { get set }

This means that it doesn't retain the delegate instance and will be set to nil when the delegate is freed.

You are creating the delegate and assigning it to a local variable myTextFieldDelegate. That variable will be freed at the end of the function, so even though you assigned myTextFieldDelegate to the myTextField.delegate, it is freed and myTextField.delegate gets set to nil because it is weak.

To fix this, create a property in your ViewController to hold the delegate object:

var myTextFieldDelegate: MyTextFieldDelegate?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download