Padin215
Padin215

Reputation: 7484

Need to know which custom UIViews are within a tap

I am creating custom UIImageViews and placing on a UIImageView in a UIScrollView. When the user taps on the custom UIImageView, it presents a popover.

The issue i may have is if two of the custom UIImageViews are overlapping. I need to ask the user which one he wants.

how can i tell which custom UIImageViews are within a tap? I need each view to return itself if it detects a tap. If more then one view returns, then i can ask the user which one he wants.

each custom UIImageView has a UITapGestureRecognizer created:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(select)];
singleTap.numberOfTapsRequired = 1;
singleTap.delegate = self;

[self addGestureRecognizer:singleTap];

right now, only the top most custom UIImageView is getting the tap and displaying the popover.

Upvotes: 0

Views: 107

Answers (2)

David Hoerl
David Hoerl

Reputation: 41642

I assume by your question that the views are transparent so the user can see that in fact there is overlap, and may intentionally tap the area of overlap.

In any case what you need to do in this case is get the location of the tap:

[tapGesture locationInView:scrollView]

Then walk the scrollView's subView array, getting each of your UIImageView's, getting its frame, and seeing if the tap is inside that frame.

Now you have an array of possible images - you can pop an action sheet (whatever) and ask the user which to show.

Upvotes: 1

Mick MacCallum
Mick MacCallum

Reputation: 130193

I'm not sure how you planned on identifying which image was which, but for this example I've used tags. The following will receive the location of a touch within the scroll view, and compare that point to frames of the image views in the scrollviews subviews. It will then add the tags of the images that matched to a mutable array.

NOTE: If you don't empty this array when you dismiss the alert new objects will be continuously added to it.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:myScrollView];

    for (UIImageView *myImageView in myScrollView.subviews) {
        if (CGRectContainsPoint(myImageView.frame, location)) {
            [someMutableArray addObject:[NSNumber numberWithInteger:myImageView.tag]];
        }
    }
}

Upvotes: 2

Related Questions