Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: An array of UIButtons

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

like image 864
achiral Avatar asked Sep 15 '11 01:09

achiral


2 Answers

Another approach is to wire the buttons up to an NSArray in Interface Builder.

@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *buttons;
like image 127
Lachlan Roche Avatar answered Oct 05 '22 15:10

Lachlan Roche


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;

.m

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];
like image 25
WrightsCS Avatar answered Oct 05 '22 14:10

WrightsCS