Ios – UIScrollview content size when orientation changes

contentsizeiosobjective cuiinterfaceorientationuiscrollview

I have a scrollview with pagination. In viewDidLoad i check if the current orientation is landscape then i set its contentsize's height 440

 if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) 
    {
        [scroll      setContentSize:CGSizeMake(self.scroll.frame.size.width*numberOfPages,340)];


    }
    else if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation]))

    {
        [scroll setFrame:CGRectMake(0,0,480,480)];
        [scroll setContentSize:CGSizeMake(self.scroll.frame.size.width*numberOfPages, 440)];


    }

everything works fine scrollview scrolls smoothy and there is no diagonal scrolling.

but when orientation changes,

i have to set scrollview's frame and contentsize again and i am setting it as follow

-(void)orientationChanged:(id)object
{
if(UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]))
{
    self.scroll.frame = [[UIScreen mainScreen]bounds];

    [scroll setContentSize:CGSizeMake(self.scroll.frame.size.width*numberOfPages, 340)];
}


else
{
 self.scroll.frame = CGRectMake(0,0,480,480);
        [scroll setContentSize:CGSizeMake(self.scroll.frame.size.width*numberOfPages, 600)];
}


}

i cant understand why i have to set content size's height upto 600 in landscape mode, and that too isnt enough. and it adds one more problem that scrollview starts scrolling diagonally which i dont want as it looks so weird. Can anyone help me understanding where and what i am missing?

i have set scrollview's autoresizing mask as

[scroll setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleHeight];

but changing it doesnt help.

Best Answer

  1. Don't use UIDeviceOrientation. Use UIInterfaceOrientation instead. DeviceOrientation has two extra options you don't need here. (UIDeviceOrientationFaceUp and UIDeviceOrientationFaceDown)

  2. Return Yes from shouldAutorotateToInterfaceOrientation

  3. Now willRotateToInterfaceOrientation: duration: will be called every time you rotate your device.

  4. Implement this method like this.

    -(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    {
    CGRect frame;
    int pageNumber = 2;
    int statusBarHeight = 20;
    
    if ((toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)) {
        frame = CGRectMake(0, 0, 480, 320 - statusBarHeight);
    } else {
        frame = CGRectMake(0, 0, 320, 480 - statusBarHeight);
    }
    
    scrollView.frame = frame;
    scrollView.contentSize = CGSizeMake(frame.size.width * 2, frame.size.height);
    } 
    

    Let,

    pageNumber = 2

    statusBarHeight = 20