Home > OS >  Protocols and functions in Swift Xcode
Protocols and functions in Swift Xcode

Time:10-06

I have a beginner question about protocols and functions in Swift. I've been following along with Angela Yu's course for about a month.

I'm trying to wrap my head around how in the code below, the function "textFieldShouldReturn" can be activated without being called.

import UIKit

class WeatherViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var conditionImageView: UIImageView!
    @IBOutlet weak var temperatureLabel: UILabel!
    @IBOutlet weak var cityLabel: UILabel!
    
    @IBOutlet weak var searchTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        searchTextField.delegate = self
       
    }

    
    @IBAction func searchPressed(_ sender: UIButton) {
        print (searchTextField.text!)
        searchTextField.endEditing(true)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print (searchTextField.text!)
        searchTextField.endEditing(true)
        return true
    }

I understand that because the WeatherViewController is connected to the protocol UITextFieldDelegate, I am able to access functions such as func textFieldShouldReturn or func textFieldShouldEndEditing. But I'm struggling to visualise what's happening behind the scenes, that makes it possible for the functions to activate when I run the program even though my code does not explicitly calls it.

If someone can explain like I'm 5, that would be greatly appreciated.

CodePudding user response:

UITextFieldDelegate is a protocol. When you have inherited your controller with this Protocol it means now all the functions(calls of this Protocol, in our case TEXTFIELD) can be received in the controller.

In viewDidLoad, you have told your specific textfield(in our case it is "searchTextField") to give you all the calls of textfield in this controller.

CodePudding user response:

The function can be activated without being called

This is the wrong sentence here. The correct one is:

The function called without me calling it!

Imagine this (although it's just a concept):

  1. Someone codes a UIButton as the return button of the keyboard.
  2. In the touchUpInside event of that button calls this:

if self.delegate?.textFieldShouldReturn?(self) ?? true {
    // Insert new line or smt.
}
  1. if the delegate is not nil and the textFieldShouldReturn is implemented in your code, your code will be called. Otherwise, a default implementation will be executed instead.

Note that it is just a concept and it is not the real implementation of the UITextField class

  • Related