从UITapGestureRecognizer获取对象的标记

时间:2014-01-01 06:00:09

标签: ios objective-c uiscrollview

我在UIScrollView子类的自定义类中使用了UIView。在该scrollview中,我添加了其他几个自定义对象(所有子类化UIView),如下所示:

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++;
    }

然后我尝试看到ColorScheme的标签做出相应的回应:

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

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

无论我做什么,始终将标记记录为零

有几点意见:

  • 我可以确认标签设置正确,并且所有ColorScheme都添加得很好。
  • 我也有tap.cancelsTouchesInView = NO,因此UIScrollView不会吞下所有接触。
  • locationInView我尝试使用self代替self.scrollView而没有运气。同样,它所在的代码位于子类UIView
  • 的类中

难以理解这一点,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:23)

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

由于您的手势被挂钩到ColorScheme对象,因此从手势识别器本身抓取视图不那么容易。