Search code examples
objective-cuitouch

How can I allow an image to be touched on a scroll view?


In my program, I use a scroll view as the background view. Then, I add several images on the scroll view. Also, I allow the users to touch the image in order to trigger some actions. However, the images attached on the scroll view cannot be detected when they were touched. I use the following code my the touch event:

UITouch * touch = [[event allTouches] anyObject];

Did I do something wrong? How can I solve this problem? Thank you very much!


Solution

  • You can use UIImageView to track touches, and also set myImageView.userInteractionEnabled = YES, since the default is no for imageviews.

    If you want to detect a tap on the image you can do this:

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlesSingleTap:)];
            [singleTap setNumberOfTapsRequired:1];
    
            [imageView addGestureRecognizer:singleTap];
    

    and implement your selector:

    - (void)handlesSingleTap:(UIGestureRecognizer *)gestureRecognizer
    {
        //Handle touch
    }