1110
1110

Reputation: 6829

Do something to selected image in scroll view

I try to make following: Horizontal list of images, that I can select and do something with it. For example flip image around x axis. I know how to rotate image. I created scrollview and load it with images. I added event handler when I tap on image. But I don't know how to do something with tapped image. How to code method to do something with tapped image?

- (void)viewDidLoad {
    [super viewDidLoad];        

    img1 = [UIImage imageNamed:@"imgTest.jpg"];
    img2 = [UIImage imageNamed:@"imgTest2.jpg"];

    arrayOfImages = [[NSMutableArray alloc] init];
    [arrayOfImages addObject:img1];
    [arrayOfImages addObject:img2];
    [arrayOfImages addObject:img1];
    [arrayOfImages addObject:img2];

    scrollView = [[UIScrollView alloc] init];
    scrollView.scrollEnabled = YES;
    scrollView.pagingEnabled = YES;
    scrollView.directionalLockEnabled = YES;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    scrollView.backgroundColor = [UIColor blueColor];
    scrollView.autoresizesSubviews = YES;
    scrollView.frame = CGRectMake(0, 0, 320, 128);
    [self.view addSubview:scrollView];

    UIImage *imageToAdd;
    int x = 0;
    int y = 0;
    for(imageToAdd in arrayOfImages)
    {
        UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];     

        temp.frame = CGRectMake(x, y, 128, 128);
        temp.userInteractionEnabled = YES;      
        x += 135;


        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
        [temp addGestureRecognizer:tap];    

        [scrollView addSubview:temp];
    }
...

- (void)imageTapped:(UIGestureRecognizer *)sender
{

    // how to get reference on selected item in scrollview???   
}

Upvotes: 1

Views: 3070

Answers (1)

DarkDust
DarkDust

Reputation: 92336

A gesture recognizer has a view property that returns the view associated with the recognizer. Since you know that it'll be a UIImageView you can simply cast it and use it as in:

UIImageView *iv = (UIImageView *)[sender view];

And your image can then be queried via:

UIImage *image = [iv image];

If you need to know the index in your array, there are two ways: either simply use [arrayOfImages indexOfObject:image];, or you can assign tags (numbers) to views and use them. A tag is not used by Apple, it's only here so we developers can "mark" views in some way. For example:

NSInteger counter = 0;
for(imageToAdd in arrayOfImages)
{
    UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
    count.tag = counter++;
    ...
}

Then, in your imageTapped:, you can query the index via tag:

NSInteger index = [imageView tag];

Upvotes: 4

Related Questions