110 Comments

Using UIScrollView with Auto Layout in iOS

Who says you can’t teach an old control some new tricks?  The UIScrollView has been around since the beginning of iOS, and there have been many blog posts, Stack Overflow questions, and Apple documentation covering how to set up your content to scroll inside a UIScrollView with the old springs & struts layout system.  

Since the introduction of Auto Layout to iOS, there is a new way you can configure your scrolling content. With Auto Layout, the amount of code you have to write is greatly reduced.

One of the big pain points with the old way of setting up a UIScrollView was communicating the content size to the scroll view. It was fairly straightforward to calculate your content size if the content in the UIScrollView was an image. But it was not as easy if your scroll view included a mixed bag of buttons, labels, custom views, and text fields. Lengthy code adjustments were needed to reflect constant changes in device rotations and phone size differences.  

In this blog post, I’ll show you how to set up a UIScrollView with Auto Layout that is responsive to portrait and landscape changes. I will also show you how the scroll view can move your content out of the way of the pop-up keyboard.

Create a Basic Layout in Interface Builder

I want to give you a sense of what we are building so you can follow along and see how the view is constructed. I created a view with some labels, text fields, and an image. If you want to follow along, I put the entire project on GitHub. Here is what it should look like in portrait and landscape.

(For demo purposes, I colored the scroll view with a yellow background and the content inside with a blue background. When in portrait mode, the content will not scroll. In landscape mode, the content can scroll vertically especially when the keyboard covers up most of the view.)

uiscrollview-complete-landscape2
uiscrollview-complete-portrait2

Adding a UIscrollView with constraints

Now let’s get started building the UI. In interface builder, drag a UIScrollView and add it as a sub view of the view controller’s main view. Now add some constraints to your scroll view to place it where you want it in your main view. In my example, the scroll view takes up the whole view, so I added four constraints from the scroll view’s edges to the main view with zero spacing. Your view hierarchy should look like the image to the right.

The following are the four constraints that I added to get the scroll view constrained to the super view.  Your constraints may look different if you do not want the scroll view to occupy the entire screen.

adding-a-uiscrollview-with-constraints3

Use a Single Child View to Hold All of Your Content

The next step in laying out our controls is to create a single child view of the UIScrollView where we will put all of our content. Using a single child view will simplify the constraints we have to add later. If your content is only a scrolling image in a UIImageView, this can serve as the single child view. In the example below, I gave the child view a name of Content View.

Contain content of UIscrollView in one UIView

Our next step is to add constraints from the content view to the scroll view. The change they made to UIScrollView, to support Auto Layout, is that it can automatically calculate the content size if you set up your constraints the right way. You need two sets of constraints.

Width or Height Constraint

Usually you only want your content to scroll in one direction. In my case I want the scroll view to scroll vertically. Therefore I need to set the width of my single content view to be the width of the scroll view. Use this equal width constraint to set the width of your content (if you are scrolling vertically) or equal height to set the height (if scrolling horizontally).

Edge Constraints

Attach four constraints (top, bottom, left, right) from our single content view to the scroll view. This might seem redundant considering we just added an equal width constraint in the previous step. However this part is the most confusing because Apple has repurposed the constraints in this case to indicate to the UIScrollView the boundaries of your content and therefore calculate the content size. These special constraints, from your content view to the UIScrollView, do not behave like normal constraints. No matter what constant value you give them, they will not resize your content view.  Once they are in place, the UIScrollView can calculate its content size. The only place I could find documentation on this new behavior is in a tech note TN2154 article by Apple. The only mention is in the section titled “Pure Auto Layout Approach”

UIScrollView with constraints on content to determine content size

Go ahead and add the top, bottom, leading, trailing, and equal width constraints from the content view to the scroll view. When finished, you will notice we are getting some Auto Layout errors. Without any controls inside the content view, or if there are no placeholder width and height constraints on the content view, the scroll view cannot determine the content size.

contentsize-is-derived-from-contentview3

Ignore the errors for now. The next step is to add whatever content you want to scroll inside the content view and use Auto Layout to constrain the items inside the content view. Make sure you have constraints attached to all four sides of the content view so that it will expand to the size of your content. If you need to, you can increase the simulated size of your view controller in interface builder to give you room to layout all of your scrolling content. To do this click on the view controller, select the size inspector and select Freeform size.

Add content to the container view

Go ahead and run the project. Your content should scroll and look good in portrait and landscape rotations.

completed landscape view
Completed portrait view

Moving Content under the Keyboard into View

If you have UITextFields near the bottom of your content view and the keyboard pops up, it blocks the bottom half of your screen; you cannot see what you are typing. The scroll view allows us to scroll the content into view.

Keyboard covers the bottom of your screen

We first need to keep track of which text field is currently being edited. You can do this many different ways, but I chose to add the view controller as a delegate to the UITextFields. In interface builder Ctrl – Drag from each UITextField to the view controller and set it as the delegate.

Add View Controller as delegate for UITextFields

Now we can implement a couple of delegate functions to keep track of which field is active. We do this to make sure that the active field is visible when the keyboard pops up.


weak var activeField: UITextField?

func textFieldDidEndEditing(_ textField: UITextField) {
    activeField = nil
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    activeField = textField
}

Now we need to register for keyboard notifications. In the viewDidLoad function, add the view controller as an observer. You can unregister from these notifications in the deinit function.


override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(SCRViewController.keyboardDidShow),
        name: UIResponder.keyboardDidShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(SCRViewController.keyboardWillBeHidden),
        name: UIResponder.keyboardWillHideNotification, object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

Finally, add an outlet to your scroll view and implement the keyboard notification selectors. If this code looks familiar, it is based on the solution from Apple’s documentation. I add the height of the keyboard to the scroll view’s content inset so that the scroll view has enough padding at the bottom to scroll the very bottom text field up above the keyboard. As the final step, I check to see if the active text field is visible and scroll the field into view if it is not.


@objc func keyboardDidShow(notification: Notification) {
    let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
    guard let activeField = activeField, let keyboardHeight = keyboardSize?.height else { return }

    let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardHeight, right: 0.0)
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
    let activeRect = activeField.convert(activeField.bounds, to: scrollView)
    scrollView.scrollRectToVisible(activeRect, animated: true)
}

@objc func keyboardWillBeHidden(notification: Notification) {
    let contentInsets = UIEdgeInsets.zero
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
}

This is what it looks like when it’s all working. Once you start editing a text field, the keyboard animates into view, and your scroll view animates the active text field to be above the keyboard. If you would like to try this code out yourself to see it in action, I have the entire project on GitHub.

uiscrollview-with-autolayout