UIScrollView and Autolayout with Swift and iOS 10

13 de Abril de 2017 por Alex Tarragó

One of the most complicated tasks with Auto Layout in iOS 8 is getting UIScrollView to work properly. We’ve been searching all over the Internet and we did not found any good documentation or tutorial about it, so after several tries we want to explain how we got UIScrollView working properly with Auto Layout on iOS8 with Swift.

…Let’s start!

First of all you’ll need to create a new project,

(Xcode menu) File > New > Project > Single View Application (in iOS/Application)

Fill whatever information you want and be sure the language is set to Swift. After this point, your screen should be similar to this one.

UIScrollView con Autolayout y Swift. Crear el proyecto para Blog de Dribba.

We are gonna use a Scroll View with paging option enabled using Auto Layout and supporting both Portrait and Landscape orientation, imaging a kind of tutorial/walkthrough for our iOS app.

1) Open the Main.storyboard and set your View Controller to use Any Width | Any Height (All possible layouts)

2) Let’s say we want three pages on our Scroll View, if you want to design them properly, you will need to resize your whole View Controller accordingly. Click on View Controller on the Document Outline and go to the Size Inspector on the Utilities menu. You’ll need to change the Simulated Size of your controller to Freeform and set it to your maximum content width. In our case, if we want 3 full-screen views, the final size will be 1800px width x 600px height.

UIScrollView con Autolayout y Swift. ¿Cómo crear nuestro ViewController? para Blog de Dribba.

3) Perfect! Everything is ready to start placing our UI elements on our View Controller. First of all let’s see what are we going to do. Our aim is to implement the following interface.

UIScrollView con Autolayout y Swift. Vista de nuestro View Controller para Blog de Dribba.

4) Place all the UI elements on the View Controller. Your view hierarchy should be like the following one.

UIScrollView con Autolayout y Swift. Árbol jerárquico ViewController para Blog de Dribba.

TRICK According to Apple’s documentation, you should have only ONE view as the container of your Scroll View.

That is why is extremely important to double-check if your view hierarchy is exactly the same as the one in the image. Your Scroll View should have only ONE view as the container of all the other scrollable views.

Constraints, constraints, constraints.

Once you have everything on their place, we should start adding all the needed constraints.

5) You will be adding constraints in an out-in approach, so you will start with the Scroll View and the Page Control.

UIScrollView con Autolayout y Swift. Añadiendo constante inferior para Blog de Dribba.
UIScrollView con Autolayout y Swift. Añadiendo constantes paso a paso para Blog de Dribba.

You’ve added 6 constraints, 4 constraints to the Scroll View (Leading, Trailing, Top and a bottom constraint to the Page Control) and 2 more constraints for the Page Control (Bottom constraint to content view and Center X constraint with the Scroll View). You can ⌘+R to see if everything is working right. You can also ⌘+→ to change the orientation of the iDevice and see how your interface is now ‘responsive’.

6) Add the Leading, Trailing, Top and Bottom constraints from the Container View. (These are special ScrollView constraints and they have no effect on your content size or position)

UIScrollView con Autolayout y Swift. Añadiendo constantes globales para Blog de Dribba.

Are you having some Storyboard errors? Let’s fix them. You just need to add two more constraints to the Container View.

UIScrollView con Autolayout y Swift. Añadiendo constantes de ancho y alto para Blog de Dribba.

You’ve added two more constraints that specify the height and the width of the Container View. Add a ‘Equal Width’ and ‘Equal Height’ as the Scroll View to the Container View. All the errors had dissappeared 🙂

7) Let’s keep adding constraints. Now is the turn of our scrollable pages. They should be referenced one to each other, so you will add the constraints having that in mind.

UIScrollView con Autolayout y Swift. Añadiendo constantes 2 para Blog de Dribba.
UIScrollView con Autolayout y Swift. Añadiendo constantes para Blog de Dribba.
UIScrollView con Autolayout y Swift. Vista 3 para Blog de Dribba.

You sould add 3 constraints to the first view (Leading, Top and Bottom), 4 constraints to the second view (leading constraint to the first view, trailing constraint to the third view, top and bottom) and 3 constraints to the third view (Top, Bottom and Trailing).

Finally, you want all the views to have the same width, so let’s do it.

UIScrollView con Autolayout y Swift. Vista 2 para Blog de Dribba.

You just added two ‘Equal Width’ constraints from the first view to the second view and from the second view to the third view.

8) You want the scrollable pages to have the same width of the ScrollView, so let’s indicate it.

Add one last ‘Equal Width’ constraint between the first view and the Scroll View.

UIScrollView con Autolayout y Swift. Vista 1 para Blog de Dribba.

Some Storyboard errors may appear after this step. If that occurs, just delete the Equal Width – Container View – Scroll View constraint.

UIScrollView con Autolayout y Swift. Constraint views for Dribba's Blog.

9) Setup the rest of the UI with your desired constraints (Page # always centered on the view). And setup the Scroll View to enable paging as follows.

UIScrollView con Autolayout y Swift. Propiedades ScrollView para Blog de Dribba.

10) Go to your ViewController.swift file and replace everything for the following piece of code.

import UIKit
    class ViewController: UIViewController, UIScrollViewDelegate {
        @IBOutlet weak var pageControl: UIPageControl!
        @IBOutlet weak var scrollView: UIScrollView!
        // MARK: – Lifecycle override func
        viewDidLoad() {
            super.viewDidLoad()
            scrollView.delegate = self
        } 
        override func didReceiveMemoryWarning() { 
            super.didReceiveMemoryWarning() 
        } 
        // MARK: – ScrollViewDelegate 
        func scrollViewDidEndDecelerating(scrollView: UIScrollView){ 
            let pageWidth: CGFloat = CGRectGetWidth(scrollView.frame) 
            var currentPage: CGFloat = floor((scrollView.contentOffset.x – pageWidth/2) / pageWidth) + 1 
            self.pageControl.currentPage = Int(currentPage) 
    } 
}

11) Connect your elements in the Storyboard with the @IBOutlet.

12) ⌘+R… and we’re done! You should be seeing something similar to this.

UIScrollView with Autolayout and Swift. Gif para Blog de Dribba.

If you got lost on any of the steps of this tutorial or you just want to have the whole finished example, you can grab it from my GitHub account.

Notícias relacionadas