10

I want to create IBOutlets and IBActions in code rather than with the interface builder.

Let's say I've got a button on my UI called btnDisplay, and a method in my code called displayMessage. What would be the code I'd have to write to make it so that when btnDisplay is tapped, displayMessage runs?

jscs
  • 63,694
  • 13
  • 151
  • 195
user3705416
  • 115
  • 1
  • 5
  • [Here][1] is a nice explanation of how to make outlets programatically. [1]: http://stackoverflow.com/questions/2544279/can-you-hard-code-ibactions-and-iboutlets-in-xcode-rather-then-drag-them-manuall – NaXir Jun 04 '14 at 04:06
  • Is this what you're talking about? http://stackoverflow.com/questions/2370031/programatically-generating-uibuttons-and-associate-those-with-ibaction Specifically, the `addTarget...` part. – Mick MacCallum Jun 04 '14 at 04:07

2 Answers2

10

The way to do that with no outlets would be to give the button a tag in IB, say 128. Then:

UIButton *btnDisplay = (UIButton *)[self.view viewWithTag:128];
[btnDisplay  addTarget:self action:@selector(pressedBtnDisplay:) forControlEvents:UIControlEventTouchUpInside];

Then implement:

- (void) pressedBtnDisplay:(id)sender {
}
danh
  • 62,181
  • 10
  • 95
  • 136
0

If you are not using IBOutlet then you can add button using code.

UIButton *btnDisplay = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[btnDisplay setTitle:@"display" forState:UIControlStateNormal];
[btnDisplay addTarget:self action:@selector(DisplayMessage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnDisplay];

If you use IBOutlet then you have to add below code in viewDidLoad or any other as per your requirement

[btnDisplay addTarget:self action:@selector(DisplayMessage:) forControlEvents:UIControlEventTouchUpInside];

and implement this method.

-(void)DisplayMessage:(id)sender
{
    //do what you want
}

Maybe this will help you.

ChintaN -Maddy- Ramani
  • 5,156
  • 1
  • 27
  • 48