0

I am creating a grid of UIViews, either 4x4, 5x5, etc. They are created using nested for loops.

UITapGestureRecognizer * touchUpInView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTouchHandler)];

for (int i = 0; i < cardsPerRow; i++) {
    for (int j = 0; j < cardsPerRow; j++) {
        UIView * myView = [[UIView alloc] initWithFrame:CGRectMake(((j + 1) * widthGap) + (j * width), (25 + ((i + 1) * heightGap)) + (i * height), width, height)];
        [myView setTag:(i * cardsPerRow + j)];
        [myView addGestureRecognizer:touchUpInView];
        [myView setBackgroundColor:[UIColor redColor]];
        [self.view addSubview:myView];
    }
}

height, heightGap, width, and widthGap are all defined as integers and just control the spacing between views and the size of the view. Bascially I want to be able to have each view be able to respond to a user tapping on it. I'm not sure if the UITapGestureRecognizer is the best approach and if so, how do I reference back to find out which view was tapped? I'm assuming that by using the tags that I have set up and passing it into the viewTouchHandler method, but how do I do that from the @selector and how would I reference it in the method? Or should I have the method take an id or UIView instead of the tag?

Ricca
  • 311
  • 4
  • 21
  • well you can assign a gesture recognizer to each view as you create it. It would then call that views selector for taps and have access to that views properties. let me edit that. you'd want to subclass UIView for this. – LanternMike Nov 11 '14 at 01:17
  • A gesture recognizer can only be associated with one view at a time. So your code ends up only have a tap gesture on the last view you create. See http://stackoverflow.com/questions/4747238/can-you-attach-a-uigesturerecognizer-to-multiple-views – rmaddy Nov 11 '14 at 01:19
  • OK so say I move it into the loop, but how do I reference them in the `viewTouchHandler` and how are they called in the `@selector`? – Ricca Nov 11 '14 at 01:49
  • Change your selector so it takes the tap gesture recognizer as a parameter. Then you can get the `view` from the gesture. – rmaddy Nov 11 '14 at 18:04

0 Answers0