Programmatically generating UIButtons and associate those with IBAction

Nicsoft picture Nicsoft · Mar 3, 2010 · Viewed 15.6k times · Source

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.

Answer

mrueg picture mrueg · Mar 3, 2010

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.