简体   繁体   English

为什么UIButton使用目标动作设计模式而不是UITextField的委派模式和反之

[英]Why UIButton uses Target Action Design Pattern not Delegate Pattern and Vice Versa for UITextField

Can any one help in understanding why Apple decides to uses Target Action design pattern for event handling of UIButton not Delegate Pattern? 有谁能帮助我们理解为什么Apple决定使用Target Action设计模式来处理UIButton而不是Delegate Pattern?

Or, I can say why Apple choose delegation Design pattern for UITextField even same thing can be achieved by Target Action also. 或者,我可以说为什么Apple为UITextField选择委托设计模式,甚至同样的事情也可以通过Target Action来实现。

There are various trade-offs to the different approaches. 对于不同的方法,需要进行各种折衷。 I think the clincher for button actions, though, is that you can add multiple target/actions to a button. 我认为按钮操作最关键的是,您可以向按钮添加多个目标/操作。 (A one-to-many relationship.) Delegation is a one-to-one relationship, so having a button trigger multiple actions, possibly to different targets, would not be possible with the delegation design pattern. (一对多关系。)委派是一对一的关系,因此使用委派设计模式不可能使按钮触发可能针对不同目标的多个动作。

I think if Apple were designing button handling now they'd use blocks/closures instead of IBActions. 我认为,如果Apple现在正在设计按钮处理,他们将使用块/闭合而不是IBAction。 The control could hold an array of blocks and the events that trigger each. 该控件可以包含一组块以及触发它们的事件。

All @IBAction functions have one of three signatures; 所有@IBAction函数均具有以下三个签名之一:

  • functionName() -> Void
  • functionName(sender: Any) -> Void
  • functionName(sender: Any, forEvent event: UIEvent) -> Void

An IBAction cannot accept any other arguments and does not return a value. IBAction不能接受任何其他参数,也不返回值。

A delegate allows the use of functions that take different parameters and return values while actions are a standard approach across UIView subclasses. 委托允许使用带有不同参数并返回值的函数,而动作是跨UIView子类的标准方法。

In some classes, such as UITextField , certain action can be handled through both delegate and action methods. 在某些类中,例如UITextField ,可以通过委托和操作方法来处理某些操作。 I guess this just gives you some choice; 我想这给您一些选择。 if you are already implementing delegate functions then you don't need to implement action handlers as well. 如果您已经在实现委托函数,则也不需要实现动作处理程序。

这是由于Apple希望在代码中显示不同的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM