Search code examples
iosswiftuikitdelegation

Where are implemented methods of delegate protocols called?


I'm new to swift and OOP programming, and I'm trying to understand delegation pattern while using UIKit. I guess I understand the concept of handing off some of class responsibilities: there is a (for example) textField instance of class UITextField which implements some logic in ViewController:

class ViewController: UIViewController {
  let textField = UITextField(frame: CGRect(...))
  override func viewDidLoad() {
    textField.contentVerticalAlignment = .center
    textField.borderStyle = .roundedRect
    textField.placeholder = "Help me to figure it out"

    textField.delegate = self // set the controller as a delegate

    self.view.addSubview(textField)
  }
}

Also there is an extension of ViewController which implements methods of UITextFieldDelegate protocol:

extension ViewController: UITextFieldDelegate {
  func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
  }

  ... // other methods
}

While reading tutorials I got the idea that logic similar to this must be implemented somewhere in UIKit:

let allowEditing = delegate?.textFieldShouldBeginEditing() ?? true

But I can't find the place where this line of code is located. Do I understand it right and what's the place of this code? I searched through the documentation and classes implementations but have not found it.


Solution

  • You got this right!

    The code you are looking for is inside private part of the UIKit and you can't see it. All implementations are private.

    Note that this method is an objective-c optional method, so it will be call like this (if it was a Swift code):

    guard delegation?.textFieldShouldBeginEditing?() ?? true else { return }
    becomeFirstResponder()
    

    see that ? before () ?

    And note that UIKit is written in objective-c, there are differences between these two languages that you should consider if you want to deep dive in them.