Is it possible to to hard code the IBAction
s and IBOutlet
s in code, instead of drag-connecting them in Interface Builder?
Asked
Active
Viewed 7,270 times
8
2 Answers
16
Yes it is poosible...
sample code
UIButton *btnDetail = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
[btnDetail setFrame:CGRectMake(250.0f, 15.0f, 65.0f, 20.0f)] ;
//btnDetail.backgroundColor = [UIColor grayColor];
[btnDetail setTitle:@"Detail" forState:UIControlStateNormal];
[btnDetail setTitleColor: [UIColor redColor] forState: UIControlStateNormal];
[btnDetail.titleLabel setFont:[UIFont fontWithName:@"Verdana" size:12]];
[btnDetail setBackgroundColor:[UIColor clearColor]];
[btnDetail sizeThatFits:btnDetail.frame.size];
[self.view addSubview:btnDetail];
//IBAction
[btnDetail addTarget:self
action:@selector(ShowSavingAccountDetail:)
forControlEvents:UIControlEventTouchUpInside];
[btnDetail setImage:[UIImage imageNamed:@"btn-detail.png"] forState:UIControlStateNormal];

Mihir Mehta
- 13,743
- 3
- 64
- 88
-
I dont know if this matters or not (because I'm new), but I had to move the IBAction portions behind the message to the view to add the button. Then confirmed it was working with an NSLog message confirming it was pressed. I tied a sender.selected == YES then print else so on and so on. – natur3 Jul 26 '15 at 21:35
13
The concept and sole purpose of IBAction and IBOutlet is to provide Interface Builder with means to connect the xib with your code.
If you don't want to use Interface Builder with your code, you don't need IBAction or IBOutlet, you need them ONLY to use objects (buttons, textfields, etc.) that were instanciated in your xib from your classes.
With that said, mihirpmehta's answer is the correct way to programmatically add UI elements to your view and add actions to them.

Marin Todorov
- 6,377
- 9
- 45
- 73