Search code examples
iphoneimageviewscrollview

How to show multiple images inside UIScrollView in iOS


I am making one iPhone app in which i need to show some images inside UIScrollView, on left and right there will be two buttons user can click on button and it will show the next or previous image. Also at the bottom there is one button, when user will click on that button it will show the image which we have selected in scrollview.I would like to know how do we show multiple images inside that scrollview and while selecting bottom button, how to find which image was there inside scrollview.


Solution

  • An example from danielbeard.wordpress.com

    In case your image names aren't just numbers:

        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    
        [scrollView setPagingEnabled:YES];
        [scrollView setAlwaysBounceVertical:NO];
    
        NSArray *imagesArray = [NSArray arrayWithObjects:@"img1.png", @"img2.png", @"img3.png", nil];
    
        for (int i = 0; i < [imagesArray count]; i++)
        {
            CGFloat xOrigin = i * scrollView.frame.size.width;
    
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, scrollView.frame.size.width, scrollView.frame.size.height)];
            [imageView setImage:[UIImage imageNamed:[imagesArray objectAtIndex:i]]];
            [imageView setContentMode:UIViewContentModeScaleAspectFit];
    
            [scrollView addSubview:imageView];
        }
    
        [scrollView setContentSize:CGSizeMake(scrollView.frame.size.width * [imagesArray count], scrollView.frame.size.height)];