Search code examples
iosiphoneios5ios6uiscrollview

How to get index of uiimage subview of uiscrollview


I need to detect selected image of uiimage which is placed inside scrollview.

My code is here:

int newscrollviewY = 40;
    for(int i = 0; i<1; i++)
    {
        scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(5, newscrollviewY, 310, 100)];
        scrollView.showsVerticalScrollIndicator = YES;
        scrollView.scrollEnabled = YES;
        scrollView.userInteractionEnabled = YES;
        scrollView.backgroundColor = [UIColor clearColor];
        scrollView.delegate=self;
        int imgx = 1;

        for(int img=0; img<[images count]; img++)
        {

            UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(imgx,0,100,100)];
            imageView1.backgroundColor = [UIColor whiteColor];
            imageView1.image = [images objectAtIndex:img];
            imageView1.contentMode = UIViewContentModeScaleAspectFit;
            [imageView1 setNeedsDisplay];
            [imageView1 setUserInteractionEnabled:YES];
            [imageView1 setMultipleTouchEnabled:YES];
            [scrollView addSubview:imageView1];


            imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
            imageButton.frame = CGRectMake(imgx,0,100,100);
            [imageButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
            imageButton.tag = img;
            [scrollView addSubview:imageButton];
            imgx = imgx + 103;


        }

Please help to detect selected image using imageButton or something else.


Solution

  • Replace your selector with buttonClicked: be Sure that you are adding ":" after selector method. follow or replace the code below:

    [imageButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    

    then Add the selector definantion in .m file

    - (void) buttonClicked: (id) sender
    {
        // here you can get the tag of button.
    
        NSInteger tag = ((UIButton *)sender).tag;
    
        // do your implementation after this
    }
    

    Hope this will solve your issue. Enjoy Coding..!!