Autolayout is changing UIScrollView's contentOffset on rotation

| | August 6, 2015

To experiment with autolayout and uiscrollview’s I have been using this example

which I have edited to include 2 views in the scroll view, I have setup the autolayout constraints to position the views horizontally adjacent with their size set to fill the scroll view frame.

UIView *beeView = [[[NSBundle mainBundle] loadNibNamed:@"BeeView" owner:nil options:nil] firstObject];
beeView.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:beeView];
UIView *beeView2 = [[[NSBundle mainBundle] loadNibNamed:@"BeeView" owner:nil options:nil] firstObject];
beeView2.backgroundColor= [UIColor orangeColor];
beeView2.translatesAutoresizingMaskIntoConstraints = NO;
[self.scrollView addSubview:beeView2];

NSDictionary *views = @{@"beeView":beeView,@"beeView2":beeView2, @"scrollView":self.scrollView};
NSDictionary *metrics = @{@"height" : @200};
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[beeView(==scrollView)][beeView2(==beeView)]|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:metrics views:views]];
[self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[beeView(==scrollView)]|" options:kNilOptions metrics:metrics views:views]];

which nicely produces what I intended.

However, if the scroll view’s contentOffset is nonzero and the device is rotated from portrait to landscape, the content offset of the scroll view is automatically set to 32px. (see screenshot)
content offset wrong

I have tried saving contentOffset and setting it to this saved value when scrollViewDidEndDecelerating: is called which works but is ugly as the scroll view scrolls to a 32px offset and then back to where I want it to be.

How do I control the scroll view’s contentOffset? Are the autolayout constraints wrong? Are there extra constraints I can add to control the contentOffset when resizing the view?

Leave a Reply