Search code examples
iphoneobjective-cuiscrollviewuiscrollviewdelegate

Replacing image in UIScrollView on selected item


I created simple UIScrollView that have images. Each time an image pressed i want to change that image, how can I do it?

I creating this UIScrollView and initializing it with NSMutableArray with images.

      UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame: CGRectMake (0,100,200,30)];
        NSMutableArray = *images = [NSMutableArray alloc] initWithObjects: img1,img2,img3,nil];

for (int i=0; i<3; i++)
{
        UIImageView *imageV = [UIImageView alloc];
        [imageV setImage:[images objectAtIndex:i]];
        [myScroll addSubview:imageV];
        [imageV release];
}


    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:@selector (changeImg:)];
    [myScroll addGestureRecognizer: singleTap];

and the toucing I'm cathing with the touched place on the scroll:

- (void) singleTapGestureCaptured:(UITapGesturerecongnizer *) gesture
{
    CGPoint touch = [gesture locationInView:myScroll];

}

By X,Y of touched item i know what image was selected

Here I need to change for example the first image of myScroll...How can i do it?


Solution

  • Add UITapGestureRecognizer on UIImageView and set its userInractionEnabled: YES which is NO by default for UIImageView.

    UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame: CGRectMake (0,100,200,30)];
    NSMutableArray = *images = [NSMutableArray alloc] initWithObjects: img1,img2,img3,nil];
    
    for (int i=0; i<3; i++)
    {
        //In your question you didn't set `imageView` frame so correct it
        UIImageView *imageV = [[UIImageView alloc]initWithFrame:yourFrame];
        [imageV setImage:[images objectAtIndex:i]];
        [imageV setUserInteractionEnabled:YES];
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:@selector (changeImg:)];
        [imageV addGestureRecognizer: singleTap];
        [myScroll addSubview:imageV];
        [imageV release];
    }
    

    After adding all imageView successfully you get them click like this :-

    -(void)changeImg:(id)sender
     {
         UIGestureRecognizer *recognizer = (UIGestureRecognizer*)sender;
         UIImageView *imageView = (UIImageView *)recognizer.view;
         [imageView setImage:[UIImage imageNamed:@"anyImage.png"]];
     }