Overriding layoutSubviews when rotating UIView

joec picture joec · Oct 29, 2010 · Viewed 9.5k times · Source

When rotating a scroll view inside a UIView, the scroll view doesnt position correctly using its default autoresizing behaviour.

Thus, when rotation occurs, in willRotateToInterfaceOrientation i call [self.view setNeedsLayout]; and my layoutSubviews method is as follows:

- (void)layoutSubviews {
    NSLog(@"here in layoutSubviews");
}

But putting a breakpoint on the method, and it never seems to enter the method.

Do i need to do something else to get it to work?

Thanks.

Answer

Paul Ardeleanu picture Paul Ardeleanu · Oct 29, 2010

willRotateToInterfaceOrientation is being called before the orientation is changed, hence your UIView will still have the old size. Try using didRotateFromInterfaceOrientation instead.

Also, for added effect, I would hide the scrollView ( maybe with inside an UIAnimation block) in willRotateToInterfaceOrientation, resize it and then show it in didRotateFromInterfaceOrientation (again, maybe inside an animation block).

Here is a snippet from one of my apps:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
self.myScroll.hidden = YES;
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView commitAnimations];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
self.myScroll.hidden = NO;
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView commitAnimations];
}

You can even do fancy stuff by checking the new orientation using UIInterfaceOrientationIsPortrait(orientation) or UIInterfaceOrientationIsLandscape(orientation).