12

I'm attempting to make a UIScrollView only allow zooming in the horizontal direction. The scroll view is setup with a pure autolayout approach. The usual approach is as suggested in a number of Stack Overflow answers (e.g. this one) and other resources. I have successfully used this in apps before autolayout existed. The approach is as follows: in the scroll view's content view, I override setTransform(), and modify the passed in transform to only scale in the x direction:

override var transform: CGAffineTransform {
    get { return super.transform }
    set {
        var t = newValue
        t.d = 1.0
        super.transform = t
    }
}

I also reset the scroll view's content offset so that it doesn't scroll vertically during the zoom:

func scrollViewDidZoom(scrollView: UIScrollView) {
    scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.frame.height)
    scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0.0)
}

This works very nicely when not using autolayout:

Zooming without autolayout

However, when using autolayout, the content offset ends up wrong during zooming. While the content view only scales in the horizontal direction, it moves vertically:

Zooming with autolayout

I've put an example project on GitHub (used to make the videos in this question). It contains two storyboards, Main.storyboard, and NoAutolayout.storyboard, which are identical except that Main.storyboard has autolayout turned on while NoAutolayout does not. Switch between them by changing the Main Interface project setting and you can see behavior in both cases.

I'd really rather not switch off autolayout as it solves a number of problems with implementing my UI in a much nicer way than is required with manual layout. Is there a way to keep the vertical content offset correct (that is, zero) during zooming with autolayout?

EDIT: I've added a third storyboard, AutolayoutVariableColumns.storyboard, to the sample project. This adds a text field to change the number of columns in the GridView, which changes its intrinsic content size. This more closely shows the behavior I need in the real app that prompted this question.

4 Answers 4

9
+300

Think I figured it out. You need to apply a translation in the transform to offset the centering UIScrollView tries to do while zooming.

Add this to your GridView:

var unzoomedViewHeight: CGFloat?
override func layoutSubviews() {
    super.layoutSubviews()
    unzoomedViewHeight = frame.size.height
}

override var transform: CGAffineTransform {
    get { return super.transform }
    set {
        if let unzoomedViewHeight = unzoomedViewHeight {
            var t = newValue
            t.d = 1.0
            t.ty = (1.0 - t.a) * unzoomedViewHeight/2
            super.transform = t
        }
    }
}

To compute the transform, we need to know the unzoomed height of the view. Here, I'm just grabbing the frame size during layoutSubviews() and assuming it contains the unzoomed height. There are probably some edge cases where that's not correct; might be a better place in the view update cycle to calculate the height, but this is the basic idea.

5
  • Thanks Anna, that's an interesting approach, and seems like it could work out well! I'll give it a shot and will report back. Feb 9, 2016 at 23:10
  • A quick test seems to indicate that this will work. I'll try integrating it into my actual project tomorrow. Thanks again! Feb 9, 2016 at 23:43
  • Sure! Let me know if it you tweak it -- I'm trying to solve the same problem. (and make sure you accept my answer ;-) Feb 9, 2016 at 23:56
  • Hi Anna, I'm having trouble getting this to work in the opposite(x) dimension. I'm getting it to work (essentially changing t.d to t.a), but when I try to do it second zoom, it jumps back to the original zoom level before zooming. I'm guessing it has something to do with the "t.y" which I'm not totally understanding, although I have been trying to set my "t.x". Any ideas. (Sorry I don't think I can post my code as a comment..)
    – narco
    Dec 11, 2016 at 20:39
  • I see this person has the same (or very similar) issue: stackoverflow.com/questions/7929237/…
    – narco
    Dec 11, 2016 at 20:39
3

Try setting translatesAutoresizingMaskIntoConstraints

func scrollViewDidZoom(scrollView: UIScrollView) {
    gridView.translatesAutoresizingMaskIntoConstraints = true
}

In the sample project it works. If this is not sufficient, try creating new constraints programmatically in scrollViewDidEndZooming: might help.

Also, if this does not help, please update the sample project so we can reproduce the problem with variable intrinsicContentSize()

This article by Ole Begemann helped me a lot
How I Learned to Stop Worrying and Love Cocoa Auto Layout

WWDC 2015 video
Mysteries of Auto Layout, Part 1
Mysteries of Auto Layout, Part 2

And so luckily, there's a flag for that. It's called translatesAutoResizingMask IntoConstraints [without space].

It's a bit of a mouthful, but it pretty much does what it says. It makes views behave the way that they did under the Legacy Layout system but in an Auto Layout world.

3
  • Thanks for the answer. I don't fully understand why this works, but I think it's essentially a fragile hack. If you turn translatesAutoresizingMaskIntoConstraints on in viewDidLoad() you immediately get a conflicting constraints exception. In any case, translatesAutoresizingMaskIntoConstraints is not meant to be used for views that are participating directly in auto layout as the GridView is here. I'll update the sample project with a variable intrinsicContentSize(). Feb 9, 2016 at 16:37
  • I've updated the example project with a storyboard that allows changing the number of columns in the grid view, which affects its intrinsic content size. (I also moved the project to GitHub). Note that with this change, your solution breaks down. If you zoom, then change the number of columns, the width constraint translated from the autoresize mask causes the GridView not to resize to fit the new number of columns. Feb 9, 2016 at 17:43
  • 1
    @Anna's answer is way better than trying to toggle between legacy and auto layout system. Feb 10, 2016 at 5:25
1

Although @Anna's solution works, UIScrollView provides a way of working with Auto Layout. But because scroll views works a little differently from other views, constraints are interpreted differently too:

  • Constraints between the edges/margins of scroll view and its contents attaches to the scroll view's content area.
  • Constraints between the height, width, or centers attach to the scroll view’s frame.
  • Constraints between scroll view and views outside scroll view works like an ordinary view.

So, when you add a subview to the scroll view pinned to its edges/margins, that subview becomes the scroll view's content area or content view.

Apple suggests the following approach in Working with Scroll Views:

  1. Add the scroll view to the scene.
  2. Draw constraints to define the scroll view’s size and position, as normal.
  3. Add a view to the scroll view. Set the view’s Xcode specific label to Content View.
  4. Pin the content view’s top, bottom, leading, and trailing edges to the scroll view’s corresponding edges. The content view now defines the scroll view’s content area.
  5. (...)
  6. (...)
  7. Lay out the scroll view’s content inside the content view. Use constraints to position the content inside the content view as normal.

In your case, the GridView must be inside the content view:

Interface Builder

You can keep the grid view constraints that you have been using but, now, attached to content view. And for the horizontal-only zooming, keep the code exactly as it is. Your transform overriding handle it very well.

3
  • I understand all this. The question is about horizontal-only zooming which is an entirely different beast than horizontal-only scrolling. In the real app that inspired this question, scrolling should work in both directions, and the height of the content view is variable. It's only zooming that should be constrained to the horizontal direction. Feb 11, 2016 at 17:54
  • No problem. The horizontal scrolling was just a guess. About the horizontal zooming, you already solved it. What remains is solving the horizontal zooming with auto layout and with that solution you can do it without Anna's. I tested and it worked fine. If there's some point unclear, please let me know and I'll edit the post. Feb 11, 2016 at 18:29
  • Anna's solution works quite well for horizontal zooming with a pure autolayout approach. If you have a different approach, I'd be interested to hear about it, though. Your answer here doesn't mention zooming. Feb 11, 2016 at 18:56
0

I'm not sure if this satisfies your requirement of 100% autolayout, but here's one solution, where the UIScrollView is set with autolayout and gridView added as a subview to it.

Your ViewController.swift should look like this:

// Add an outlet for the scrollView in interface builder.
@IBOutlet weak var scrollView: UIScrollView!

// Remove the outlet and view for gridView.
//@IBOutlet var gridView: GridView!

// Create the gridView here:
var gridView: GridView!

// Setup some views
override func viewDidLoad() {
    super.viewDidLoad()
    // The width for the gridView is set to 1000 here, change if needed.
    gridView = GridView(frame: CGRect(x: 0, y: 0, width: 1000, height: self.view.bounds.height))
    scrollView.addSubview(gridView)
    scrollView.contentSize = CGSize(width: gridView.frame.width, height: scrollView.frame.height)
    gridView.contentMode = .ScaleAspectFill
}

func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return gridView
}

func scrollViewDidZoom(scrollView: UIScrollView) {
    scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0.0)
    scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.frame.height)
}
2
  • Thanks for the nice answer. Unfortunately, the whole reason I want to use autolayout is that "GridView" (not actually so simple as GridView in my sample project) has a size that changes based on its contents. Autolayout's support for intrinsicContentSize() is perfect for this. Without it, the view(s) have to be manually resized as their content changes which is fairly painful. I don't actually mind turning autolayout for the scroll view off as long as its content view can be sized via its intrinsic content size. Feb 8, 2016 at 20:16
  • Ah, gotcha. I'll let you know if I figure out a way for using autolayout on the gridView as well!
    – xoudini
    Feb 8, 2016 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.