Images in a Scroll View

I know that when I was a beginning iPhone developer doing things that seem so simple now weren’t so simple back then. Just because I didn’t know any better and was unaware of the tools and API’s available to me.

One thing that I’ve been doing a lot recently is putting several images in a UIScrollView, so I thought I’d post the barebones version of the code here in case anyone finds it useful. Hopefully I’ll be able to add more snippets in the future.

#define IMAGE_WIDTH   320
#define IMAGE_HEIGHT  416
       
- (void)viewDidLoad
{
    [super viewDidLoad];
       
    NSArray *photos = nil;      // TODO – fill with your photos
       
    // note that the view contains a UIScrollView in aScrollView
       
        int i=0;
        for ( NSString *image in photos )
        {
                UIImage *image = [UIImage imageNamed:[photos objectAtIndex:i]];
                UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                imageView.contentMode = UIViewContentModeScaleAspectFit;
                imageView.clipsToBounds = YES;
               
                imageView.frame = CGRectMake( IMAGE_WIDTH * i++, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
               
                [aScrollView addSubview:imageView];
                [imageView release];
        }
        aScrollView.contentSize = CGSizeMake(IMAGE_WIDTH*i, IMAGE_HEIGHT);
        aScrollView.delegate = self;
}

Leave a Comment