Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting tag of object from UITapGestureRecognizer

I have a UIScrollView used inside a custom class that subclasses UIView. Within that scrollview, I have added several other custom objects (all subclassing UIView as well) like so:

UITapGestureRecognizer *tap;

    for (int count = 0; count < ColorSchemeCount; count++) {
        //Check for next page first
        [self managePageAdditions];

        //Set up the scheme
        ColorScheme *scheme = [[ColorScheme alloc]
                               initWithFrame:[self determineSchemeCircleFrameFromCount:pageCheck]
                               title:[self getColorSchemeTitleFromIndex:pageCheck]
                               colors:[self getColorSchemeFromIndex:pageCheck]];
        scheme.tag = pageCheck;
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(schemeTouchedAtIndex:)];
        tap.cancelsTouchesInView = NO;
        [scheme addGestureRecognizer:tap];
        [self.scrollView addSubview:scheme];

        //See if next pass requires a new page or not
        if(pageCheck > 0) needsNextPage = (pageCheck % kSchemesPerPage == 0);
        needsNextPage ? pageCheck = 0 : pageCheck++;
    }

And then I try to see the ColorScheme's tag to respond accordingly:

- (void)schemeTouchedAtIndex:(UITapGestureRecognizer *)gesture{
    CGPoint touchPointInSuperview = [gesture locationInView:self.scrollView];
    ColorScheme *touchedView = (ColorScheme *)[self.scrollView hitTest:touchPointInSuperview withEvent:nil];

    NSLog(@"%li", (long)touchedView.tag);
}

And no matter what I seem to do, it always logs the tag as zero.

A couple of observations:

  • I can confirm the tags are being set properly, and all the ColorScheme are being added just fine.
  • I also have the tap.cancelsTouchesInView = NO so the UIScrollView won't swallow all the touches.
  • In the locationInView I have tried using self instead of self.scrollView to no luck. Again, the code where this resides is in a class subclassing UIView.

Stumped on this one, any help is much appreciated.

like image 920
Jason Renaldo Avatar asked Jan 01 '14 06:01

Jason Renaldo


Video Answer


1 Answers

-(void)schemeTouchedAtIndex:(UITapGestureRecognizer *)gesture{
NSLog(@"%ld", gesture.view.tag);
}

Since your gestures are hooked to the ColorScheme object its less hacky to grab the view from the gesture recognizer itself.

like image 76
David Wong Avatar answered Oct 02 '22 22:10

David Wong