16

How do I do if I want to programatically generate a set of buttons and then associate those with IBActions? It's easy if I add the buttons in Interface Builder, but that I cannot do for this case.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nicsoft
  • 3,644
  • 9
  • 41
  • 70

2 Answers2

32

The buttons have the method - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents.

The code to use this would look like this:

UIButton *myButton = [[UIButton alloc] init...];
[myButton addTarget:something action:@selector(myAction) forControlEvents:UIControlEventTouchUpInside];

This assumes that your IBAction is named myAction and that something is the controller for which that action is defined.

eds
  • 449
  • 2
  • 10
mrueg
  • 8,185
  • 4
  • 44
  • 66
  • When speciying a selector for a UIButton do you have to name a method with a single argument, the selected buttons id? What would happen if I specified a method with no args? – mmccomb Mar 03 '10 at 11:09
  • 1
    @mattmccomb: From the documentation: "The action message may optionally include the sender and the event as parameters, in that order." You can have a method with zero, one or two arguments as the action. But don't forget to add the : at the end of the action name for each argument. – mrueg Mar 03 '10 at 16:09
6

First, create the button:

UIButton * btn;

btn = [ [ UIButton alloc ] initWithFrame: CGRectMake( 0, 0, 200, 50 ) ];

Then adds an action:

[ btn addTarget: self action: @selector( myMethod ) forControlEvents: UIControlEventTouchDown ];

Then adds the button to a view:

[ someView addSubView: btn ];
[ btn release ];

UIControl reference UIButton reference

Macmade
  • 52,708
  • 13
  • 106
  • 123