Tom Reay Tom Reay - 1 year ago 83
iOS Question

iOS scroll view bounds not equal to superview bounds

I've got a UIScrollView that has constraints pinning it to the superview's leading and trailing edges (not the margins). In this scroll view I have a UIImage which I'm setting to initially be the full width of the scroll view. On the iPhone 7 this works correctly, the image is full width

However on the iPhone 7 Plus there is a gap between the edge of the image and the edge of the screen. The scroll view is full width as when I zoom the image in it does go right to the edge.

I'm getting the image to match the scroll view width by setting

imageView.frame = scrollView.bounds
imageView.contentMode = .scaleAspectFill

The issue seems to be the scroll view bounds. On the iPhone 7 Plus the scroll view width is reported as 375, however the screen width is reported as 414. On the iPhone 7 the scroll view width is 375 and the screen width is also 375.

Anyone know why this is? I'm sure I'm misunderstanding something!

Answer Source

Most probably your problem is that scrollView's frame is not updated yet when you use it to set imageView's frame.

Try to move layout code into viewDidLayoutSubviews instead:

override func viewDidLayoutSubviews() {
    imageView.frame = scrollView.bounds
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download