Horizontal paged UIScrollView with a gap between each view -- views aren't centered

2.7k Views Asked by At

Apple's WWDC 2010 Tutorial Video "Designing Apps with Scroll Views" works well with iOS 4, but with iOS 5 the pages are not centered:

enter image description here

It seems that

pagingScrollViewFrame.origin.x -= PADDING;

doesn't work in iOS 5.

My code is the following:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

#define PADDING  10

- (void)loadView 
{    

    // Step 1: make the outer paging scroll view
    CGRect pagingScrollViewFrame = [[UIScreen mainScreen] bounds];
    pagingScrollViewFrame.origin.x -= PADDING;
    pagingScrollViewFrame.size.width += (2 * PADDING);

    pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
    pagingScrollView.pagingEnabled = YES;
    pagingScrollView.backgroundColor = [UIColor whiteColor];
    pagingScrollView.showsVerticalScrollIndicator = NO;
    pagingScrollView.showsHorizontalScrollIndicator = NO;
    pagingScrollView.contentSize = CGSizeMake(pagingScrollView.bounds.size.width * 6, pagingScrollView.bounds.size.height);
    pagingScrollView.delegate = self;
    self.view = pagingScrollView;

    for(int i = 0; i < 6; i++)
    {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor blueColor];

        CGRect bounds = pagingScrollView.bounds;
        CGRect pageFrame = bounds;
        pageFrame.size.width -= (2 * PADDING);
        pageFrame.origin.x = (bounds.size.width * i) + PADDING;
        view.frame = pageFrame;
        [pagingScrollView addSubview:view];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [[UIApplication sharedApplication] setStatusBarHidden:YES   
                                    withAnimation:UIStatusBarAnimationSlide];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

What can I do?

1

There are 1 best solutions below

5
On
pageFrame.origin.x = (bounds.size.width * i) + PADDING;

change this part to

pageFrame.origin.x = (bounds.size.width + PADDING) * i;