Reputation: 2058
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.
Upvotes: 1
Views: 2031
Reputation: 27506
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.
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];
}
Upvotes: 6
Reputation: 15722
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];
}
Upvotes: 2