ninjaRoche
ninjaRoche

Reputation: 62

How can I create an array of buttons in xcode?

I have a view containing 80 UIButtons, and 80 UIImages. Rather than refer to these by individual outlet references, I would like to refer to them as indexes in an array, and so be able to change the Image, and work out which UIButton is sending a message without specific references.

I am sure this must be possible, as there is no way having 80 different versions of the same code is correct way to do this!

Is this possible?

Upvotes: 0

Views: 3545

Answers (2)

mbm29414
mbm29414

Reputation: 11598

You may be better served by looking into UICollectionView, but to answer the question as asked:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.buttonArray = [NSMutableArray array];
    for (int i = 0; i < 80; i = i + 1) {
        // However you wish to get your button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, i * 20, 20, 10);
        [self.view addSubview:button];
        // Other button-specific stuff (like setting the image, etc.)
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttonArray addObject:button];
    }
}
- (void)buttonPressed:(UIButton *)sender {
    int index = [self.buttonArray indexOfObject:sender];
    // Now handle the button press based
}

Upvotes: 3

Alexander
Alexander

Reputation: 21

It is possible, it’s called outlet collection.

@property(nonatomic,retain) IBOutletCollection NSArray *buttonsArray;

Upvotes: 1

Related Questions