【问题标题】:What is the difference between addTarget(_:action:for:) and sendAction(_:to:for:) UIControl instance methods?addTarget(_:action:for:) 和 sendAction(_:to:for:) UIControl 实例方法有什么区别?
【发布时间】:2018-05-09 14:09:38
【问题描述】:

我正在继承UIControl,因为我想将我的视图控制器设置为目标,所以我发现了 sendAction 方法。我真的无法弄清楚这两种方法之间的区别以及它们各自的用法何时更合适。

【问题讨论】:

    标签: ios swift selector uicontrol


    【解决方案1】:

    不同之处在于sendAction(_:to:for:)实际上立即调用定义的选择器,而addTarget(_:action:for:)将目标和动作与控件关联并且只调用选择器当事件发生时。

    【讨论】:

    • 换句话说,你的UIControl子类的实现调用sendAction来通知任何监听事件的人。您的自定义控件的用户调用addTarget。您的自定义控件实现不会使用addTarget,只会使用sendAction
    【解决方案2】:

    您可以使用sendAction:to:forEvent: 来模拟实际的底层系统调用。即:模拟用户实际点击UIButtonUIControl)并将UIControlEventstouchUpInside 发送到目标。我个人以前从未使用过它。

    addTarget:action:forControlEvents: 映射选择器UIControlEvent 和目标,以供以后使用,例如当用户点击UIButton 时。

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 1970-01-01
      • 2015-04-18
      • 2010-12-13
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      相关资源
      最近更新 更多