子视图上的手势识别器似乎不起作用

时间:2012-03-20 11:08:26

标签: objective-c uigesturerecognizer

我的代码如下:

- (void)setPosts:(NSArray *)posts
{
    _posts = posts;


    int totalHeight = 0;
    for (TumblrPost *post in posts) {
        totalHeight += post.thumbH;
    }
dispatch_queue_t mainQ = dispatch_get_main_queue();
dispatch_async(mainQ, ^{
    int cumulativeY = 0;
    int postCount = 0;
    for (TumblrPost *post in posts) {
        NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"ThumbnailView" owner:nil options:nil];            
        ThumbnailView* thumbnail = [array objectAtIndex:0];
        thumbnail.frame = CGRectMake(0,cumulativeY,0,0);
        thumbnail.userInteractionEnabled = YES;

        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showMainImage:)];
        [thumbnail addGestureRecognizer:gesture];

        [self.multiThumbnailView addSubview:thumbnail];
        [thumbnail loadUrl:post.url];   

        cumulativeY+=100;//post.thumbH;
        if(postCount >=2)
            break;
        postCount++;
    }
    NSLog(@"Set posts method");
});
}

- (void)showMainImage:(UITapGestureRecognizer *)gesture
{
    if(gesture.state == UIGestureRecognizerStateChanged || gesture.state == UIGestureRecognizerStateEnded)
    {
        int thumbIndex = [self.multiThumbnailView.subviews indexOfObject:gesture.view];
        self.selectedPost = (TumblrPost*)[self.posts objectAtIndex:thumbIndex];

        [self performSegueWithIdentifier:@"ShowMainPost" sender:self];
    }
}

multiThumbnailView是我在故事板中的UIView,ThumbnailView是一个xib / class组合,它是一个100x100的正方形,其中有一个标签,上面写着'test'。

当我运行我的代码时,我在垂直线上得到三个盒子但是当我点击我的子视图时手势识别器不会触发。一切都有userInteractionEnabled勾选。我尝试在主multiThumbnailView上制作一个测试手势识别器,并且有效。

请帮忙!

1 个答案:

答案 0 :(得分:4)

我的猜测是ThumbnailViewUIImageView的子类 - 默认情况下会将userInteractionEnabled设置为NO

确保在每个userInteractionEnabled = YES上设置ThumbnailView您想拦截的点按。

修改

此外,您将ThumbnailView的框架设置为大小为(0,0)。 这意味着这个视图基本上是不可见的,因此不会拦截触摸。

最后,请不要这样做:

ThumbnailView* thumbnail = [array objectAtIndex:0];

相反,您可以检查数组的计数或只是:

ThumbnailView* thumbnail = [array lastObject];