Search code examples
iosuiscrollviewscroll-paging

UIScrollview starts at page 3 of 5, not 1 of 5


I have created a view (called masterView) with a CGRect of x=160, y=186, width=1600, height=380. This view contains 5 subviews, each one iphone screen wide (360).

I have set up a scrollview with paging in order to page through this view. When I run the app, page 3 of 5 appears, I can page freely between 3 - 5 + 2 blank pages after 5, but I can't page to pages 1 & 2. So for some reason masterView is shoved over to the left by 2 screen widths. How do I correct its position so that the app starts at page 1?

This is my first app.

I have put the following code in the view controller's viewDidLoad:

CGRect screenRect = CGRectMake(0, 0, 320, 380);

UIScrollView *scrollView2 = [[UIScrollView alloc] initWithFrame:screenRect];
[scrollView2 setDelegate:self];

CGRect bigRect = CGRectMake(0, 186, 1600, 380);
[scrollView2 setContentSize:bigRect.size];
[scrollView2 setPagingEnabled:YES];

[scrollView2 addSubview:masterview];
[[self view] addSubview:scrollView2];

Solution

  • Check out this excellent tutorial on using a UIScrollView with a UIPageControl. It should get you going.

    http://www.iosdevnotes.com/2011/03/uiscrollview-paging/

    The important bit is in the viewDidLoad:

    for (int i = 0; i < colors.count; i++) {
        CGRect frame;
        frame.origin.x = self.scrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = self.scrollView.frame.size;
    
        UIView *subview = [[UIView alloc] initWithFrame:frame];
        subview.backgroundColor = [colors objectAtIndex:i];
        [self.scrollView addSubview:subview];
        [subview release];
    }
    

    Although this code sample uses ARC, it still applies. Note that the frame for each subview is offset by the page number self.scrollView.frame.size.width * i.

    Good luck.