Fix UIScrollview content auto-layout issues!

Is your UIScrollView content not behaving properly when you rotate your iOS app?  Would you like it to re-render, re-format, etc. upon rotation?  Read on:

Make sure you do a few things:

  1. Re-set the frame for the content subview of the UIScrollView to the new scrollview dimensions (the new dimensions will not propagate down to the subview if the subview is created manually, etc.)
  2. Re-set the content size for the content subview of the UIScrollView
  3. Either set your view content modes to ‘redraw’, or manually call SetNeedsDisplay()

You can put all this code in your ViewController, via overriding this function (complete with sample code for the above commands):


public override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
self.myUIScrollView.contentOffset = CGPointZero //scroll up to top before changing dimensions - will eliminate render drift
self.myUIScrollView.contentSize = CGSizeMake(self.mainContentAreaScrollView.bounds.width, 1100) //the width of your content will change, but not the length, so either cardcode length or determine the length through other means
for subby in self.myUIScrollView.subviews{ //now lets find the UIScrollView's content view and change its frame dimensions
if subby is UIViewForContentOfScrollView {
(subby as! UIViewForContentOfScrollView).frame = CGRectMake(myUIScrollView.bounds.origin.x, myUIScrollView.bounds.origin.y, myUIScrollView.bounds.width, 1100); //length of frame needs to match the length of contentSize you set earlier
}
}
}

Ok, if that looks ugly in your browser, just cut and paste into your favorite code editor.  Ugh wordpress.

Enjoy, comment with any questions.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s