I'm trying to implement a UIScrollView
the New Way, using Auto Layout. I've set up constraints from the inner view to the scroll view so that it can compute its own contentSize
automatically, and that works like a charm— except that all hell breaks loose when I try to zoom in or out. I can't even properly describe what happens, other than to say that the inner view gets "messed up".
You can see an example of this behavior here (not my project; you have to set the scroll view's maximumZoomScale
and implement -viewForZoomingInScrollView:
before zooming will work).
Has anyone else run into this behavior? Is there currently any way to get zooming in a UIScrollView
to work with Auto Layout without essentially re-implementing the zooming behavior yourself?
The best answer that I have seen is Mark's (https://stackoverflow.com/users/1051919/mark-kryzhanouski), posted here: UIScrollView Zoom Does Not Work With Autolayout.
The crux of it is that you have to anchor the image view that is nested in the scroll view, to the parent of the scroll view. Despite the guidance in the iOS 6 release notes, it is not intuitive to me what view is "floating" over what. In this case, the scrolling view is just a single image view.
I did do a lot of experimentation with this, hoping to find an all-IB approach and found none. You can still generate the view hierarchy in IB, but you still have to programatically add constraints. You can delete some or all of the default constraints (mainly just to appease the constraint-conflict warnings), but you always need Mark's code to tie the image view to the parent of the scroll view, the grand-parent of the image view.
It seems like it should be simpler than this - it "should just work" but:
Complete Swift Playground Example
The simplest example I can think of is adding a
UIImageView
to aUIScrollView
. This is 100% in code, you'll just need to add a PNG to the Playground. I called mineImage.png
. In a Playground you'll see the whole thing rendered in the 'Live View'. Pinch-zoom works using a Ctrl-click to place one finger on the screen and then dragging around. Until the content is zoomed in bigger than the screen panning will not work. Double-tap the image to toggle between 1x and 3x scale.Based upon the Apple's Technical Note TN2154: UIScrollView and Autolayout
Gotcha
You'll find the whole thing very frustrating if your content is not bigger than the screen size. If your content completely fits on screen nothing will happen. That's why you must get zooming to work too. If you want to prove to yourself it works, test with a really big image (bigger than the window).
Without adding an imageView in the storyboard, I've found the following works perfectly: