Kodeco Forums

Video Tutorial: Swift Scroll View School Part 4: Centering

In this video tutorial, you'll learn how to center your content within a scroll view.

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3911-scroll-view-school/lessons/5


how do you center and account have it stick to edges so no black background can be seen?

I like that it looks for the center but when rotating, sometimes, depending on the center, the black background is there. how do i have the image moved to edges so no black background is shown?


Transitioning from a size with a corresponding positive edge inset.left, means it cannot have a new x offset, no matter the zoom level. Transitioning to a view with positive edge inset.left means do not mess with it at all. Finally, transitioning where neither original nor final size has an inset requires the new offset to be clipped into its allowed range. Otherwise a negative offset or too large an offset will leave a gap between image and scrollview.

Use the non-challenge ViewController and alter viewWillTransitionToSize to the code below. It’s not pretty but it does the job.!

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {

// viewWillLayoutSubviews() has already been called 
let originalInset = scrollView.contentInset
let centerPoint = CGPoint(x: scrollView.contentOffset.x + CGRectGetWidth(scrollView.bounds) / 2,
  y: scrollView.contentOffset.y + CGRectGetHeight(scrollView.bounds) / 2)

coordinator.animateAlongsideTransition({ (context) -> Void in
let newInset = self.scrollView.contentInset
let offsetX: CGFloat
if newInset.left > 0 {
    // don't mess with it. Use the existing value.
    offsetX = self.scrollView.contentOffset.x
} else if originalInset.left > 0 {
    // calculate for centred image
    offsetX = (self.scrollView.contentSize.width - size.width) / 2
} else {
    // clip in order to keep the contentSize within correct scroll bounds
    offsetX = max(min(centerPoint.x - (size.width / 2), self.scrollView.contentSize.width - size.width), 0)
let offsetY: CGFloat
if newInset.top > 0 {
    offsetY = self.scrollView.contentOffset.y
} else if originalInset.top > 0 {
    offsetY = (self.scrollView.contentSize.height - size.height) / 2
} else {
    offsetY = max(min(centerPoint.y - (size.height / 2), self.scrollView.contentSize.height - size.height), 0)
self.scrollView.contentOffset = CGPoint(x: offsetX, y: offsetY)
  }, completion: nil)