Search code examples
uiimageviewsubviewuitouchuitapgesturerecognizeruiresponder

how to detect which subview is touched programmatically


I have searched a lot over the net but have not been able to find out anything specific. I guess it is not a very big issue, but I am unable to figure it out.

I am working on a UIImageView "A", and then I add some other UIImageViews as the subview of that "A ImageView". UserInteraction is enabled for all the subViews. Now in TouchBegan method I get the array of subviews of "A ImageView" and compare it with Touch.view. but touch.view is always equal to the parent i.e. "A ImageView" and never returns the touched subView.

So please guide me how to detect which subView is touched, and then further I will be moving that subview to a new location by updating its center.

Thanking you all in advance and looking forward to your response.

Regards,


Solution

  • I'm afraid it's wrong to use imageview as buttons, but if you insists to do this, try these:

    You can re-write the hitTest method by subclassing an imageview

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
    {
        UIView *hittedView = [super hitTest: point withEvent: event];
        NSLog (@"self=<%p>, hitted=<%p>", self, hittedView);
        return hittedView;
    }
    

    add logs to see if the default hitTest returns correct subview.

    If it doesn't, I'm afraid you have to write hitTest code by your self:

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event 
    {
        for (UIView *view in self.subviews) {
            if (CGRectContainsPoint(view.frame, point)) {
               return view;
            }
        }
        return self
    }
    

    This document is useful for you: http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/Introduction/Introduction.html