1

I would like tone able to cut these lines down:

[button0 addGestureRecognizer:longPress];
[button1 addGestureRecognizer:longPress];
[button2 addGestureRecognizer:longPress];
[button3 addGestureRecognizer:longPress];
[button4 addGestureRecognizer:longPress];
[button5 addGestureRecognizer:longPress];
[button6 addGestureRecognizer:longPress];
[button7 addGestureRecognizer:longPress];
[button8 addGestureRecognizer:longPress];
[button9 addGestureRecognizer:longPress];

etc.. all the way to 36!!

Possibly with a loop? But i'm not sure how to do this.

Thanks, Regards.

Neil
  • 2,004
  • 3
  • 23
  • 48

2 Answers2

6

You can assign a tag to each button and loop through the buttons using the method viewWithTag.

for (int i = 0; i < 36; i++) {
    UIButton *button = [self.view viewWithTag:i];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    [button addGestureRecognizer:longPress];
}

The following screenshot shows where to assign the tag for each button in Interface Builder.

enter image description here

If you have setup IBOutlets for the buttons, you can obtain them using valueForKey: and without the tag:

for (int i = 0; i < 36; i++) {
    NSString *key = [NSString stringWithFormat:@"button%d", i];
    UIButton *button = [self valueForKey:key];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    [button addGestureRecognizer:longPress];
}
sch
  • 27,436
  • 3
  • 68
  • 83
  • Awesome, I just added this into my code and it works beautifully! Is it more efficient to use the tag method or to use the IBOutlets? In terms of running the program, not time required to code it. – Neil Mar 13 '12 at 14:42
  • Either method you choose will not impact the performance of your app. – sch Mar 13 '12 at 15:37
2

Put your buttons in an array and use fast enumeration to iterate over them.

NSArray *buttons = [NSArray arrayWithObjects:button0, button1, button2, button3, button4, button5, button6, button7, button8, button9, nil];

for (UIButton *button in buttons) {
    [button addGestureRecognizer:longPress];
} 
jonkroll
  • 15,682
  • 4
  • 50
  • 43
  • thanks, I have another question if you don't mind. How do you have multiple button working with one gesture recognizer, because when i do this only the last one works – Neil Mar 13 '12 at 01:14
  • Ah, that's a good point. You can't attach the same gesture recognizer to more than one view. You should create the gesture recognizer within your loop, so a new instance is created with each iteration. See example of this here in this answer: http://stackoverflow.com/a/7883902/663476 – jonkroll Mar 13 '12 at 01:21
  • Thanks for the link and the help! – Neil Mar 13 '12 at 02:32