1

I have the following code which adds the UITapGestureRecognizer to a UIImageView:

UIImageView *circleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"red_circle"]];
    [circleView setUserInteractionEnabled:YES];

    [circleView setFrame:CGRectMake(20 + 60 * ([self.tasks count] - 1), self.bounds.size.height - 300, 44, 44)];

    // register gestures
    [self registerGestureRecognizer:circleView];

    [self addSubview:circleView];


-(void) registerGestureRecognizer:(UIImageView *) circleView
{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    tapGestureRecognizer.delegate = self; 
    [circleView addGestureRecognizer:tapGestureRecognizer];
}

-(void) tapped:(UITapGestureRecognizer *) recognizer
{
    NSLog(@"tapped!");
}

But when I touch the image the tapped method is never called! Am I missing something.

The view which contains the UIImageView is added to the UIScrollView.

UPDATE: Here is the code that adds a TaskView to the UIScrollView

-(TaskView *) createTaskView
{
    TaskView *taskView = [[TaskView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

    taskView.userInteractionEnabled = YES;

    taskView.backgroundColor = [UIColor clearColor];

    [taskView.textView setDelegate:self];

    return taskView;
}

-(void) initializeScrollViewWithTasks
{
    for(int day = 1; day <= 7; day++)
    {
        TaskView *taskView = [self createTaskView];
        taskView.tag = day;
       // [_taskViews addObject:taskView];
        [self.scrollView addSubview:taskView];
    }
}

SOLUTION:

Totally my fault! I was doing something crazy when adding items to the UIScrollView. Fixed it!

4

1 回答 1

1

您需要将userInteractionEnabledUIImageView 的此属性设置为“是”。像这样替换您的代码:

-(void) registerGestureRecognizer:(UIImageView *) circleView
{
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
    tapGestureRecognizer.delegate = self; 
    tapGestureRecognizer.numberOfTapsRequired = 1;
    circleView.userInteractionEnabled=YES;
    [circleView addGestureRecognizer:tapGestureRecognizer];
}

-(void) tapped:(UITapGestureRecognizer *) recognizer
{
    NSLog(@"tapped!");
}
于 2013-10-02T18:07:13.583 回答