0

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?

4
  • 4
    Sounds like you want to use a UICollectionView? Commented Mar 12, 2014 at 12:25
  • make array of buttons Commented Mar 12, 2014 at 12:26
  • Go for UICollectionView. will be more appropriate for this Commented Mar 12, 2014 at 12:28
  • how does the view looks like.. all elements vertically/horizontally or like a grid where you will show images and buttons Commented Mar 12, 2014 at 12:46

2 Answers 2

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

It is possible, it’s called outlet collection.

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

1 Comment

It looks like from what I'm seeing that you need to manually set the type of the objects contained in the array. In your case, you could use UIButton if they're all going to be buttons, but you could also use id for a diverse collection. Something like this: @property(nonatomic,retain) IBOutletCollection(UIButton) NSArray *buttonsArray; From the little testing I've done with it, it looks like it will put them in the array in the order that you hook them up in IB (so the first button you connect will be at index 0, the second at index 1, etc).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.