Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically generating UIButtons and associate those with IBAction

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.

like image 382
Nicsoft Avatar asked Mar 03 '10 09:03

Nicsoft


People also ask

What is IBOutlet and IBAction in Swift?

@IBAction is similar to @IBOutlet , but goes the other way: @IBOutlet is a way of connecting code to storyboard layouts, and @IBAction is a way of making storyboard layouts trigger code. This method takes one parameter, called sender . It's of type UIButton because we know that's what will be calling the method.

How do you make UIButton programmatically in swift 5?

Show activity on this post. import UIKit import MapKit class MapViewController: UIViewController { override func loadView() { mapView = MKMapView() //Create a view... view = mapView //assign it to the ViewController's (inherited) view property. //Equivalent to self. view = mapView myButton = UIButton(type: .


2 Answers

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.

like image 68
mrueg Avatar answered Sep 21 '22 00:09

mrueg


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

like image 36
Macmade Avatar answered Sep 21 '22 00:09

Macmade