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

469 views Asked by At

Can any one help in understanding why Apple decides to uses Target Action design pattern for event handling of UIButton not Delegate Pattern?

Or, I can say why Apple choose delegation Design pattern for UITextField even same thing can be achieved by Target Action also.

3

There are 3 answers

0
Duncan C On

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. The control could hold an array of blocks and the events that trigger each.

5
Paulw11 On

All @IBAction functions have one of three signatures;

  • 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.

A delegate allows the use of functions that take different parameters and return values while actions are a standard approach across UIView subclasses.

In some classes, such as UITextField, certain action can be handled through both delegate and action methods. 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.

0
Arpit On

This is due to Apple wanting to show different patterns in code.