Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

swift2

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.

like image 712
Josh Avatar asked Apr 09 '16 09:04

Josh


1 Answers

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.

like image 108
mcfedr Avatar answered Sep 21 '22 07:09

mcfedr