Josh Josh - 1 year ago 61
Swift Question

How does self.textField.delegate = self work in swift?

I am working with keyboard resign features in iPhone app development. I would like to know why

self.textField.delegate = self

needs to be included into the viewDidLoad of a viewController. I have tried to find reasons of this but no explanation has been clear so far.


A few points

  1. The reason you need to set the delegate is because without it the view doesn't know about the view controller. So it wouldn't know about your method textFieldDidEndEditing and it would never be called.

  2. That is the basic premise of delegate, you are telling that object, "here is an object that I want you to call methods on"

  3. It doesn't have to be set in viewDidLoad - but it's often the most convient place to set up delegates for views.

  4. The delegate doesn't have to be the view controller (self), in your case it's the simplest way, but with a UITableView its common to have another class be the delegate so that all the logic isn't in one place and so it can be changed.