【问题标题】:Question about Delegate / Protocol requirements关于代表/协议要求的问题
【发布时间】:2021-09-10 04:28:50
【问题描述】:

所以我只是让我的 ViewController 符合UITextFieldDelegate

我的理解是:

Delegate 只是一个协议。协议有一些要求,在UITextFieldDelegate 的情况下,其中一些看起来像..

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

     func textFieldDidBeginEditing(_ textField: UITextField)

     //etc, etc.
}

为什么我没有实现任何方法时没有编译错误?它们是不需要的,还是 UIViewController 已经隐式地符合这些方法?

【问题讨论】:

标签: swift


【解决方案1】:

Objective-C 协议(分别继承自 NSObjectProtocol 的协议)可以声明它们的要求 optional。事实上,大多数委托都会声明所有方法optional。这意味着您不必实现这些方法,当您选择不这样做时,会实现一些默认行为。

【讨论】:

    【解决方案2】:

    您的代码 sn-p 与 UITextFieldDelegate 协议的定义不太一样。两个观察结果:

    • 文本字段委托协议不包含delegate 属性。

      是的,文本字段有一个delegate 属性:

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

      但委托协议不需要视图控制器中的delegate 属性(或您指定为委托的任何内容)。

    • 方法是optional

      实际定义如下(按shift-command-o或“文件”»“快速打开... ”,确保选择了 Swift 按钮,然后搜索 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
      
          ...
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      相关资源
      最近更新 更多