Adding a multiple images to a UIScrollView (iOS)

This is the code that I use when setting up a UIScrollView to contain multiple images that can be scrolled through. I add this code in the viewDidLoad or viewWillAppear methods and then set the numberOfViews to the number of images I want to display. This will also scale the images to fit the size of the screen using an aspect fit scaling. The example code loads images named “image_1”, “image_2” etc.

-(void) setupScrollView {
    //add the scrollview to the view
   self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 
                                           self.view.frame.size.width, 
                                           self.view.frame.size.height)];
   self.scrollView.pagingEnabled = YES;
   [self.scrollView setAlwaysBounceVertical:NO];
    //setup internal views
   NSInteger numberOfViews = 3;
   for (int i = 0; i < numberOfViews; i++) {
      CGFloat xOrigin = i * self.view.frame.size.width;
      UIImageView *image = [[UIImageView alloc] initWithFrame:
                                                CGRectMake(xOrigin, 0, 
                                                self.view.frame.size.width, 
                                                self.view.frame.size.height)];
      image.image = [UIImage imageNamed:[NSString stringWithFormat:
                                        @"image_%d", i+1]];
      image.contentMode = UIViewContentModeScaleAspectFit;
      [self.scrollView addSubview:image];
    }
    //set the scroll view content size
   self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * 
                                            numberOfViews, 
                                            self.view.frame.size.height);
    //add the scrollview to this view
   [self.view addSubview:self.scrollView];
}
Advertisements

3 thoughts on “Adding a multiple images to a UIScrollView (iOS)

  1. Maybe I am stupid, but when I insert the code into my viewDidLoad, I get an error saying “use of undeclared identifier ‘setupScrollView'”. Where do you declare setupScrollView? I am new to Obj-C and I have just started teaching myself, so I have trouble with the small things! Haha

    Anyway, thanks so much and hopefully you can help me out! Thanks
    -Cassie

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s