If I have a large number of buttons set up in Interface Builder, how can I place them into an array via code?
For example, if I have three buttons and in the interface file I define them:
@property (nonatomic, retain) IBOutlet UIButton *button1;
@property (nonatomic, retain) IBOutlet UIButton *button2;
@property (nonatomic, retain) IBOutlet UIButton *button3;
If I want to rename each of these buttons to say "Hello", I want to be able to lump them into an array and then use a function such as:
for (int i = 0; i < someArray.count; i++)
{
someArray[i].text = @"Hello";
}
Could someone please provide information on how this is achieved (if it's possible)?
Thanks
Another approach is to wire the buttons up to an NSArray in Interface Builder.
@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *buttons;
The following code will add 5 buttons, each with a new tag and also connect it to an event. The buttons will be placed side by side with a 5px padding:
If you plan on accessing the button outside of the for{}
scope below, you can define your button in your header, otherwise, you can define it inside the scope. UIButton * settButton;
CGFloat staticX = 5; // Static X for all buttons.
CGFloat staticWidth = 60; // Static Width for all Buttons.
CGFloat staticHeight = 56; // Static Height for all buttons.
CGFloat staticPadding = 5; // Padding to add between each button.
for (int i = 0; i < 5; i++)
{
settButton = [UIButton buttonWithType:UIButtonTypeCustom];
[settButton setTag:i];
[settButton setFrame:CGRectMake((staticX + (i * (staticHeight + staticPadding))),5,staticWidth,staticHeight)];
[settButton setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%i.png",i]] forState:UIControlStateNormal];
[settButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchDown];
[settButtonView addSubview: settButton];
}
[self.view addSubview: settButtonView];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With