Ali Hassan
Ali Hassan

Reputation: 519

Add images to UIScrollView horizontally with paging

I am trying to display images in a horizontal row using pages,with each page containing 4 images probably separated by a little space of one line or without space. As the user scrolls horizontally, next four images are displayed in the center of view. But using this code:

 UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, screenHeight/4, screenWidth, screenHeight/4)];
    scroll.showsHorizontalScrollIndicator = YES;
    scroll.showsVerticalScrollIndicator=NO;
    scroll.pagingEnabled = YES;
    NSInteger numberOfViews = 3;
    int k=1;
    for (int i = 0; i < numberOfViews; i++) {
        CGFloat xOrigin = i * self.view.frame.size.width;
        UIView *awesomeView = [[UIView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
        awesomeView.backgroundColor = [UIColor colorWithRed:0.5/i green:0.5 blue:0.5 alpha:1];
        [scroll addSubview:awesomeView];
        for (int j=0; j<4; j++) {
            NSString *imageName = [NSString stringWithFormat:@"image%d.png", k];
            UIImage *image = [UIImage imageNamed:imageName];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            CGRect imageFrame=CGRectMake(0, k*screenHeight/4, screenWidth/5, screenHeight/5);
            imageView.frame=imageFrame;
            [awesomeView addSubview:imageView];
            k++;
        }

images are displayed vertically on first page view. Moreover it looks like vertical scrolling is working. What I am missing?

Upvotes: 1

Views: 2133

Answers (1)

Jakub
Jakub

Reputation: 13860

In this line:

CGRect imageFrame=CGRectMake(0, k*screenHeight/4, screenWidth/5, screenHeight/5);

You are messing with frame your imageView (inside UIView - awesomeView).

Your k variable is 1,2,3,4

So i assume that you have 4 imageViews in vertical, and next 'column' with four image on the left, right?

Also you don't set contentSize for your scrollView anywhere so, you might not see the second 'column'

Upvotes: 1

Related Questions