Sergio Bost
Sergio Bost

Reputation: 3209

Question about Delegate / Protocol requirements

So I just made my ViewController conform to UITextFieldDelegate.

They way I understand it is:

A Delegate is simply a protocol. Protocols have some requirements, in the case of UITextFieldDelegate some of them would look like..

protocol UITextFieldDelegate: class { 
     var delegate: (Not sure of this type actually) { get set }
    
     func textFieldDidEndEditing(_ textField: UITextField) 

     func textFieldDidBeginEditing(_ textField: UITextField)

     //etc, etc.
}

Why did I get no compile errors when I hadn't implemented any of the methods? Are they some how not required or does UIViewController implicitly already conform to these methods?

Upvotes: 1

Views: 163

Answers (2)

Rob
Rob

Reputation: 437432

Your code snippet is not quite how UITextFieldDelegate protocol is defined. Two observations:

  • The text field delegate protocol does not include a delegate property.

    Yes, the text field has a delegate property:

    @available(iOS 2.0, *)
    open class UITextField : UIControl, UITextInput, NSCoding, UIContentSizeCategoryAdjusting {
    
        ...
    
        weak open var delegate: UITextFieldDelegate? // default is nil. weak reference
    
        ...
    }
    

    But the delegate protocol has no requirement for a delegate property in the view controller (or whatever you specify as the delegate).

  • The methods are optional.

    The actual definition is as follows (found by pressing shift-command-o or “File” » “Open Quickly...”, making sure the Swift button is selected, and then searching for UITextFieldDelegate):

    public protocol UITextFieldDelegate : NSObjectProtocol {
    
        @available(iOS 2.0, *)
        optional func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool // return NO to disallow editing.
    
        @available(iOS 2.0, *)
        optional func textFieldDidBeginEditing(_ textField: UITextField) // became first responder
    
        @available(iOS 2.0, *)
        optional func textFieldShouldEndEditing(_ textField: UITextField) -> Bool // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
    
        @available(iOS 2.0, *)
        optional func textFieldDidEndEditing(_ textField: UITextField) // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
    
        ...
    }
    

Upvotes: 2

Schottky
Schottky

Reputation: 2014

Objective-C protocols (resp. protocols that inherit from NSObjectProtocol) can declare their requirements optional. In fact, most delegates will declare all methods optional. This means that you won't have to implement the methods, when you choose not to do so some default behavior is implemented.

Upvotes: 1

Related Questions