Search code examples
iphoneiosuiscrollviewuitouch

Detect touch of UIImage added as subview of UIScrollView


I have UIScrollView with many UIImageViews.I need to drag and drop image from UIScrollView to another view. Outside the scrollView touch is worked. But inside scroll view touch is not worked. I used touchesBegan,touchesMoved etc method. Please help me.

-(IBAction)selectBut:(id)sender
{

 scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(x,y,w,h)];

 scrollView.userInteractionEnabled = YES;

 int y = 0;

 for (int i = 0; i < [myArray count]; i++) {

UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, y, 75, 30)];

 image.userInteractionEnabled = YES;

  y=y+35;

 [scrollView addSubview:image];

}

[self.view addSubview:scrollView];

[scrollView setContentSize:CGSizeMake(150, 300)]

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

   UITouch *touch = [touches anyObject];

    if ([touch tapCount] == 1) {

        NSLog(@"One touch !!");
    }

}

Solution

  • you need to customize the UIImageView with your own view inherited from UIImageView. Provide touch methods in that customized subclass and add it on your UIScrollView..

    Subviews of UIScrollview will never call touchesBegan method directly. You need to customized with subview to get touchesBegan properties of that added subview/customized view.

    I mean to say take subclass of ImageView like

    CustomImageView *imageView = [[CustomImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    [imageView setUserInteractionEnabled:YES];
    [scrollView addSubview:imageView];
    [imageView release];
    

    CustomImageView class is should be inherited from UIImageView like

     @interface CustomImageView : UIImageView
      {
      }
    

    in # .m File

      #import "CustomImageView.h"
    
    @implementation CustomImageView
    
    
        - (id)initWithFrame:(CGRect)frame
       {
    self = [super initWithFrame:frame];
    if (self) {
    
    }
    return self;
    }
    
    
    
        - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
          NSLog(@"%s", __FUNCTION__);
    
         }
    
        - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
    
        }
    
        - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
    
        UITouch *touch = [touches anyObject];
    
          if ([touch tapCount] == 2) {
        drawImageView.image = nil;
        return;
        }
    
         }