I have 39 different UIButton variables in my .h file, but I would like to add each of them to an array without having to type out the same thing 39 times.
Is there a way that I could do this in a for loop?
The buttons are named accordingly: btn1,btn2,btn3 etc.
You might want to forego the 39 buttons in your header file and instead have a single array.
I suspect that you want to use manual references so you can take advantage of Interface Builder, to control events and layout. I suggest doing something a little different.
Create a single property – an
NSMutableArray. Then, when the view loads, create the buttons on the fly.To access a button, use something like
[self.arrayOfButtons objectAtIndex:38];. (In the case of 39 buttons, that would return the last button.);`To create a button, you use the following:
Note that you pass in the frame of your button’s
initmethod. The frame of your button is going to start in the top left corner of its container and your button will be 100 pixels square. The frame is an instance ofCGRect. (You create aCGRectby calling the functionCGRectMake(x,y,width,height).To make 39 buttons, you might want to loop as follows, given an array to hold the buttons,
myButtonsand predefinednumberOfButtonsand dimension variables:Of course, you are going need to set unique values for
x,y,widthandheightfor each button or they will all overlap. Once you’ve created your buttons, you can do things with them, like set the label, or show them onscreen. To show them onscreen, you can do something like this:Of course, just adding buttons to the screen is useless. You need to be able to make them do something. To add an action to a button, you can use:
The first part,
addTarget:self, says that this view controller handles the event that you’re going to ask it to handle.action:@selector(someMethod:)tells the class what method to perform when the event occurs. Then,forControlEvents:UIControlEventTouchDownsays that the said class should perform the said method when the button is tapped.So, in your header:
And in your implementation, you can use this:
Now, you can go to button paradise without taking Interface Builder on the plane. Go UIButton happy!