Home > Enterprise >  How to layout a horizontal image into a UIScrollView?
How to layout a horizontal image into a UIScrollView?

Time:11-17

How to layout a horizontal image in a scrolling view with the storyboard, so that the horizontal image can scroll in different directions ?

Tried all the options that were on the internet. Solutions with a vertical image work, but not with a horizontal.

CodePudding user response:

The basics for centering the scroll content on start...

Assuming:

  • constraints are setup correctly
  • imageView is the view returned by viewForZooming()

Implement:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    
    let x = (imageView.frame.width - scrollView.frame.width) * 0.5
    let y = (imageView.frame.height - scrollView.frame.height) * 0.5
    scrollView.contentOffset = CGPoint(x: x, y: y)
    
}

Note that this is only the basics... depending on what else you may be doing, viewDidLayoutSubviews() can be called multiple times throughout the life-cycle. So you'd want to account for that (unless you want the view centered every time).

  • Related