Scrollview ios

Scrollview ios DEFAULT

UIScrollView Tutorial: Getting Started

Update note: Ron Kliffer updated this tutorial for Xcode 11, Swift 5 and iOS 13. Ray Wenderlich wrote the original.

is one of the most versatile and useful controls in iOS. It’s the basis for the very popular and it’s a great way to present content that’s larger than a single screen.

In this tutorial, you’ll create an app similar to the default iOS Photos app and learn all about . You’ll learn how to:

  • Use to zoom and view a very large image.
  • Keep ‘s content centered while zooming.
  • Use for vertical scrolling with Auto Layout.
  • Prevent the keyboard from hiding text input components.
  • Use to allow scrolling through multiple pages of content.

This tutorial assumes you understand how to use Interface Builder to add objects and connect outlets between your code and storyboard scenes. If you’re not familiar with Interface Builder or storyboards, work through our storyboards tutorial before starting this one.

Getting Started

Use the Download Materials button at the top or bottom of this tutorial to download the starter project, then open it in Xcode. Build and run using an iPhone 8 simulator to see what you’re starting with. Continue using the iPhone 8 simulator for the rest of the tutorial.

Image too big for the device to display

You’ll see that you have several photos available in your project. You can select a photo to see it full-sized, but sadly, the device’s limited size prevents you from seeing the whole photo.

What you really want is to fit the image to the device’s screen by default and zoom to see details, just like the Photos app does.

Can you fix it? Yes, you can!

Scrolling and Zooming a Large Image

To kick off this tutorial, you’ll set up a scroll view that lets the user pan and zoom an image.

Open Main.storyboard and drag a Scroll view from the Object Library onto the document outline, right below View on the Zoomed Photo View Controller scene. Then, move Image View inside your newly-added Scroll View. Your document outline should now look like this:

Document outline for Zoomed Photo View Controller

See that red arrow? Xcode is complaining that your Auto Layout rules are wrong.

To fix them, select Scroll View and click the Pin button at the bottom of the storyboard window. Add four new constraints: top, bottom, leading and trailing. Set each constraint’s constant to 0 and uncheck Constrain to margins. The result should look like this:

Scroll view's constraints

Now, select Image View and add the same four constraints on it. Make sure to pin the constraints to the Scroll View and not the Frame Layout Guide, like this:

Image view's constraints

Build and run.

Swipe to see the full image

Thanks to the scroll view, you can now swipe to see the full-size image! But what if you want to zoom in and out? Or what if you want to see the picture scaled to fit the device’s screen?

You’ll need to write code for those cases!

Panning and Zooming Your Image

Open ZoomedPhotoViewController.swift and add the following outlets inside the class declaration:

@IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var imageViewTrailingConstraint: NSLayoutConstraint!

Back in Main.storyboard, set the outlet to Scroll View and set the Scroll View’s to Zoomed Photo View Controller. Also, connect the new constraint outlets to the appropriate constraints in the document outline, like this:

Setting the Zoomed Photo View Controller's constraints

Back in ZoomedPhotoViewController.swift, add the following to the end of the file:

extension ZoomedPhotoViewController: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } }

This makes conform to and implements . The scroll view calls this method to determine which of its subviews to scale when the user pinches the image. Here, you tell it to scale .

Setting the Zoom Scale

Next, add the following inside the class, right after :

func updateMinZoomScaleForSize(_ size: CGSize) { let widthScale = size.width / imageView.bounds.width let heightScale = size.height / imageView.bounds.height let minScale = min(widthScale, heightScale) scrollView.minimumZoomScale = minScale scrollView.zoomScale = minScale }

This method calculates the zoom scale for the scroll view. A zoom scale of 1 indicates that the content displays at its normal size. A zoom scale of less than 1 shows a zoomed-out version of the content, and a zoom scale greater than 1 shows the content zoomed in.

To get the minimum zoom scale, you first calculate the required zoom to fit the image view snugly within the scroll view, based on its width. You then calculate the same for the height. You take the minimum of the width and height zoom scales, and set this value for both and of .

You’ll initially see the entire image fully zoomed-out, and after zooming in, the user will be able to zoom out to this level, too.

Since the defaults to 1, you don’t need to set it. If you set it to greater than 1, the image may appear blurry when the user zooms in on it. If you set it to less than 1, you won’t be able to zoom in to the full image’s resolution.

Finally, you need to update the minimum zoom scale each time the controller updates its subviews. Add the following right before the previous method to do this:

override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() updateMinZoomScaleForSize(view.bounds.size) }

Build and run; you should get the following result:

Zooming to enlarge photo

Now, when you tap on an image, it fits on the screen. You can pan around it and zoom in or out. Awesome!

Note: If you’re unfamiliar with how to perform pinch gestures on the simulator, try holding the Option key while clicking and dragging.

However, there’s still one problem: The image is pinned to the top of the scroll view. It’d sure be nice to center it instead, right?

Centering Your Image

Still in ZoomedPhotoViewController.swift, add the following inside the class extension, right after

//1 func scrollViewDidZoom(_ scrollView: UIScrollView) { updateConstraintsForSize(view.bounds.size) } //2 func updateConstraintsForSize(_ size: CGSize) { //3 let yOffset = max(0, (size.height - imageView.frame.height) / 2) imageViewTopConstraint.constant = yOffset imageViewBottomConstraint.constant = yOffset //4 let xOffset = max(0, (size.width - imageView.frame.width) / 2) imageViewLeadingConstraint.constant = xOffset imageViewTrailingConstraint.constant = xOffset view.layoutIfNeeded() }

Now, go over this step-by-step:

  1. The scroll view calls each time the user zooms. In response, you simply call and pass in the view’s bounds size.
  2. gets around an annoyance with : If the scroll view’s content size is smaller than its bounds, it places the contents at the top-left of the screen, rather than the center.
  3. You center the image vertically by subtracting the height of from the ‘s height and dividing the result in half. This value adds padding to the top and bottom constraints.
  4. Similarly, you calculate an offset for the leading and trailing constraints of , based on the width of the view.

Pat yourself on the back, then build and run your project! Select an image and you’ll end up with a lovely, centered image that you can zoom and pan. :]

Zooming and panning the image

Scrolling Vertically

Now, suppose you want to change PhotoScroll to display the image at the top and add comments below it. Depending on how long the comment is, you may end up with more text than your device can display. to the rescue!

Note: In general, Auto Layout considers the top, left, bottom and right edges of a view to be the visible edges. However, scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the edges within a scroll view actually refer to the edges of its Content view.

To size the scroll view’s frame with Auto Layout, you need to either make the constraints regarding the width and height of the scroll view explicit, or you must tie the edges of the scroll view to views outside of its own subtree.

You can read more in this technical note from Apple.

Next, you’ll learn how to fix the width of a scroll view, which is really its content size width, using Auto Layout.

Scroll View and Auto Layout

Open Main.storyboard and lay out a new scene.

First, add a new View Controller. In the Size inspector, replace Fixed with Freeform for the Simulated Size, then enter a width of 340 and a height of 800.

New view controller settings

You’ll notice the layout of the controller gets narrower and longer, simulating the behavior of a long, vertical piece of content. The Simulated Size helps you visualize the display in Interface Builder. It has no runtime effect.

Uncheck Adjust Scroll View Insets in the Attributes inspector for your newly-created view controller.

Attributes inspector settings

Add a Scroll view that fills the entire space of the view controller.

Add leading and trailing constraints with constant values of 0 to the view controller. Make sure to uncheck Constrain to margins. Add top and bottom constraints from Scroll view to the Top and Bottom Layout guides, respectively. They should also have constants of 0.

Add a view as a child of the Scroll view and resize it to fit the entire space of the Scroll view.

Rename its storyboard Label to Container View. Like before, add top, bottom, leading and trailing constraints, with constants of 0, and uncheck Constrain to margins. Again, make sure to pin the constraints to the Scroll view and not the Frame Layout Guide.

To fix the Auto Layout errors, you need to specify the Container View’s size. You want it to be as wide as the scroll view, so attach an equal-width constraint from the Container View to the Scroll view. For Container View’s height, define a height constraint of 500.

Note: Auto Layout rules must comprehensively define a scroll view’s . This is the key step in correctly sizing a scroll view when using Auto Layout.

Add an Image View inside Container View.

In the Attributes inspector, specify photo1 for the image, choose Aspect Fit for the mode and check Clip to Bounds.

Changing photo1's settings in the Attributes inspector

Add top, leading and trailing constraints to Container view like before, and add a height constraint of 300.

Adding a Label to Your Image

Add a Label inside Container View below the image view. Specify the label’s text as What name fits me best? and add a centered horizontal constraint relative to Container View. Next, add a vertical spacing constraint of 0 with the UIImage.

Add a text field inside of Container View, below the new label. Add leading and trailing constraints to Container View with constant values of 8 and no margin. Next, add a vertical-space constraint of 30 relative to the label.

Your document outline should now look like this:
View Controller Scene's document outline

Now, you need to connect a segue to your new View Controller.

To do so, first delete the existing show segue between the Photo Scroll scene and the Zoomed Photo View Controller scene. Don’t worry, you’ll add all the work you’ve done on Zoomed Photo View Controller back to your app later.

In the Photo Scroll scene, control-drag from PhotoCell to the new View Controller and add a show segue. Make the identifier showPhotoPage.

Build and run.

Image with caption in vertical view

Displaying Properly in Every Orientation

You can see that the layout displays correctly when the device is in vertical orientation. Try rotating to landscape orientation. Oops!

In landscape, there’s not enough vertical room to show all the content, yet the scroll view allows you to properly scroll to see the label and the text field. Unfortunately, since the image in the new View Controller is hard-coded, you won’t see the image you selected in the Collection view.

To fix this, you need to pass the image name to the View Controller when the segue executes.

Scrolling to See More

Go to File ▸ New ▸ File…, choose the iOS ▸ Source ▸ Cocoa Touch Class template and click Next. Name the class PhotoCommentViewController and set the subclass to UIViewController. Make sure that the language is set to Swift. Click Next and save it with the rest of the project.

Now, replace the contents of PhotoCommentViewController.swift with this code:

import UIKit class PhotoCommentViewController: UIViewController { //1 @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var nameTextField: UITextField! //2 var photoName: String? override func viewDidLoad() { super.viewDidLoad() //3 if let photoName = photoName { self.imageView.image = UIImage(named: photoName) } } }

Here’s what this code does, step-by-step:

  1. Adds s for the UI elements.
  2. Adds a property to represent the presented image’s name.
  3. Sets the image on using .

Back in the storyboard, open the Identity inspector for View Controller and select PhotoCommentViewController for the Class. Then, wire the IBOutlets for the scroll view, image view and text field.

Open CollectionViewController.swift, and replace with this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UICollectionViewCell, let indexPath = collectionView?.indexPath(for: cell), let viewController = segue.destination as? PhotoCommentViewController { viewController.photoName = "photo\(indexPath.row + 1)" } }

This sets the name of the photo your app will display on whenever the user taps one of the photos.

Build and run.

Image with scrolling capability

Your view nicely displays the content and, when needed, allows you to scroll down to see more. However, you’ll notice two issues with the keyboard: First, when entering text, the keyboard hides the text field. Second, there’s no way to dismiss the keyboard.

Ready to fix the glitches?

Managing the Keyboard

Unlike , which automatically handles moving content out of the way of the keyboard, you have to manage the keyboard manually when you use a directly.

Do this by making observe the keyboard objects that iOS sends whenever the keyboard hides and displays.

To do this, open PhotoCommentViewController.swift and add the following methods:

//1 func adjustInsetForKeyboardShow(_ show: Bool, notification: Notification) { guard let userInfo = notification.userInfo, let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } let adjustmentHeight = (keyboardFrame.cgRectValue.height + 20) * (show ? 1 : -1) scrollView.contentInset.bottom += adjustmentHeight scrollView.verticalScrollIndicatorInsets.bottom += adjustmentHeight } //2 @objc func keyboardWillShow(_ notification: Notification) { adjustInsetForKeyboardShow(true, notification: notification) } @objc func keyboardWillHide(_ notification: Notification) { adjustInsetForKeyboardShow(false, notification: notification) }

Here’s what you’re doing with this code:

  1. In , you extract the keyboard height from the ‘s and set the scroll view’s insets accordingly.
  2. You call when the user hides or shows the keyboard, indicating the direction to move the scroll view.

Next, you need to set up the observers for the keyboard changes. Add the following code at the bottom of :

NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

Dismissing the Keyboard

To dismiss the keyboard, add this method to PhotoCommentViewController.swift:

@IBAction func hideKeyboard(_ sender: AnyObject) { nameTextField.endEditing(true) }

This method will resign the first responder status of the text field, which, in turn, dismisses the keyboard.

Finally, open Main.storyboard, and drag a Tap Gesture Recognizer onto the View in the Photo Comment View Controller scene. Then, wire it to the in .

To make it more user friendly, the keyboard should also dismiss when the user presses the return key. Right-click on and wire Primary Action Triggered to .

Build and run.

Keyboard shows and hides itself correctly

Now, navigate to the Photo Comment View Controller scene. Tap the text field and then tap somewhere else on the view. The keyboard should properly show and hide itself relative to the other content on the screen. Likewise, tapping the return key does the same.

Paging With UIPageViewController

In the third section of this tutorial, you’ll create a scroll view that allows paging, meaning that the scroll view locks onto a page when you stop dragging. You can see this in action in the App Store app when you view screenshots of an app.

Getting Set Up

Go to Main.storyboard and drag a Page View Controller onto the canvas. Open the Identity inspector and enter PageViewController for the Storyboard ID.

In the Attributes inspector, the Transition Style is set to Page Curl by default. Change it to Scroll and set the Page Spacing to 8.

Transition style settings

In the Photo Comment View Controller scene’s Identity inspector, specify a Storyboard ID of PhotoCommentViewController. This lets you refer to the storyboard from your code.

Open PhotoCommentViewController.swift and add this property after the others:

var photoIndex: Int!

This references the index of the photo to display. The page view controller will use this property.

Creating and Implementing Your Page View Controller

Now, create a new file with the iOS ▸ Source ▸ Cocoa Touch Class template. Name the class ManagePageViewController and set the subclass to UIPageViewController.

Open ManagePageViewController.swift and replace the contents of the file with the following:

import UIKit class ManagePageViewController: UIPageViewController { var photos = ["photo1", "photo2", "photo3", "photo4", "photo5"] var currentIndex: Int! override func viewDidLoad() { super.viewDidLoad() // 1 if let viewController = viewPhotoCommentController(currentIndex ?? 0) { let viewControllers = [viewController] // 2 setViewControllers(viewControllers, direction: .forward, animated: false, completion: nil) } } func viewPhotoCommentController(_ index: Int) -> PhotoCommentViewController? { guard let storyboard = storyboard, let page = storyboard .instantiateViewController(withIdentifier: "PhotoCommentViewController") as? PhotoCommentViewController else { return nil } page.photoName = photos[index] page.photoIndex = index return page } }

Here’s what this code does:

  1. creates an instance of through the storyboard. You pass the name of the image as a parameter so the displayed view matches the image you selected in the previous screen.
  2. You set up the by passing it an array that contains the single view controller you just created.

Now that you’ve taken care of that, you need to implement . Add the following class extension to the end of this file:

extension ManagePageViewController: UIPageViewControllerDataSource { func pageViewController( _ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let viewController = viewController as? PhotoCommentViewController, let index = viewController.photoIndex, index > 0 { return viewPhotoCommentController(index - 1) } return nil } func pageViewController( _ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let viewController = viewController as? PhotoCommentViewController, let index = viewController.photoIndex, (index + 1) < photos.count { return viewPhotoCommentController(index + 1) } return nil } }

allows you to provide content when the page changes. You provide view controller instances for paging both forward and backward. In both cases, you use to determine which image is currently displayed.

Both methods use the parameter to indicate the currently-displayed view controller. Using the , it creates and returns a new controller.

You also need to set the . Add the following to the end of :

dataSource = self

There are only a couple things left to do to get your page view running. First, you'll fix the flow of the app.

Fixing Your App's Flow

Switch back to Main.storyboard and select your newly-created Page View Controller scene. In the Identity inspector, specify ManagePageViewController for its class.

Delete the push segue showPhotoPage you created earlier. Then control-drag from Photo Cell in Scroll View Controller to Manage Page View Controller Scene and select a Show segue. In the Attributes inspector for the segue, specify its name as showPhotoPage, as you did before.

Open CollectionViewController.swift and change the implementation of to the following:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UICollectionViewCell, let indexPath = collectionView?.indexPath(for: cell), let managePageViewController = segue.destination as? ManagePageViewController { = photos managePageViewController.currentIndex = indexPath.row } }

Build and run.

Scrolling to page between images

You can now scroll sideways to page between different detail views.

Displaying a Page Control Indicator

For the final part of this tutorial, you'll add a to your app.

Fortunately, has the ability to automatically provide a .

To do so, your must have a transition style of and you must implement two special methods on .

You previously set the Transition Style – great job! All you need to do now is add these two methods inside the extension on :

func presentationCount(for pageViewController: UIPageViewController) -> Int { return photos.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return currentIndex ?? 0 }

Here's what this code does:

  • In , you specify the number of pages to display in the page view controller.
  • In , you tell the page view controller which page it should initially select.

After you've implemented the required delegate methods, you can add further customization with the API.

To try it out, go to AppDelegate.swift and replace with this:

func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let pageControl = UIPageControl.appearance() pageControl.pageIndicatorTintColor = UIColor.systemGray pageControl.currentPageIndicatorTintColor = UIColor.systemPurple return true }

This will customize the colors of the .

Build and run.

Customizing your page controls

Putting It All Together

Almost there! The very last step is to add back the zooming view when the user taps an image.

Open PhotoCommentViewController.swift and add the following to the end of the class:

//1 @IBAction func openZoomingController(_ sender: AnyObject) { self.performSegue(withIdentifier: "zooming", sender: nil) } //2 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let id = segue.identifier, let viewController = segue.destination as? ZoomedPhotoViewController, id == "zooming" { viewController.photoName = photoName } }

Take a look at this code, step-by-step:

  1. The action for opening the zooming view simply calls with the zooming segue identifier.
  2. In , you send the destination controller's value to the image the user selected.

In Main.storyboard, add a Show Detail segue from Photo Comment View Controller to Zoomed Photo View Controller. With the new segue selected, open the Identity inspector and set the Identifier to zooming.

Select the Image View in Photo Comment View Controller, open the Attributes inspector and check User Interaction Enabled. Drag a Tap Gesture Recognizer onto the image view and connect it to .

Now, when you tap an image in Photo Comment View Controller Scene, you'll go to the Zoomed Photo View Controller Scene where you can zoom the photo.

Build and run one more time.

Completed iOS Photos clone

You did it! You've created an iOS Photos app clone. You can select and navigate through a collection view of images by swiping, and you can zoom the photo content.

Where to Go From Here?

Download the completed version of the project using the Download Materials button at the top or bottom of this tutorial.

You’ve delved into many of the interesting things that a scroll view is capable of doing. If you want to go further, there's an entire video series dedicated to scroll views. Take a look.

Now, go make some awesome apps, safe in the knowledge that you’ve got mad Scroll view skillz!

If you run into any problems along the way, or want to leave feedback about what you've read here, join the discussion in the comments below. Weekly

The newsletter is the easiest way to stay up-to-date on everything you need to know as a mobile developer.

Get a weekly digest of our tutorials and courses, and receive a free in-depth email course as a bonus!


Table of contents:

  1. Structure of scroll view
  2. Content Layout guide and Frame Layout guide
  3. Step 1: Put a scroll view into the view controller and set constraints
  4. Step 2 : Put a view inside the scroll view and set constraints
  5. Step 3: Placing UI Elements inside Content view

Before moving on to how to use a scrollview in storyboard / XIB, I think it's crucial to discuss the structure of scroll view to prevent getting "ambiguous scrollable content width / height" error message in Interface Builder.

scrollview ambiguity

Structure of scrollview

Scrollview works by having a scrollable content area, like this:

scroll view structure

In order for scrollview to work in Auto Layout, scrollview must know its scrollable content (scrollview content) width and height , and also the frame (X, Y , Width, Height) of itself, ie. where should the superview place scrollview and what size.

Xcode will show you the error "ambiguous scrollable content width / height" if Auto Layout doesn't know what is the width and height for the scrollable content inside scrollview.

Content Layout guide and Frame Layout guide

In Xcode 11, Apple has introduced Content Layout Guide and Frame Layout Guide for Scroll View in Interface Builder, which makes it easier to design UI inside Scroll View. This is enabled by default.

content layout guide checkbox

To layout a scrollview correctly, we will need two set of constraints :

  1. Constraints that set the size and position of the scroll view relative to its superview.
  2. Constraints that set the size of the scrollable content area inside the scrollview, so the scroll view can know the scrollable content dimension and render correctly.

The Frame Layout guide relates to the position (x, y) and size (width, height) of the scrollview itself, relative to the superview it was placed in.

Frame Layout guide

The Content Layout guide relates to the size of the scrollable content area inside the scroll view.

content layout guide

The challenging part is to define enough constraints to let Auto Layout calculate the scrollable content area (Content Layout) width and height, which we will go into in the next section.

Download the sample scroll view project
Not sure if you are doing it right on the scroll view layout?

Download the sample project and compare it yourself!

Step 1: Put a scroll view into the view controller and set constraints

First, place a scroll view into the view controller, and set some constraints for it so Auto Layout can know how to position and size it.

Usually I will pin it to the edges (top, leading, trailing and bottom) of the safe area like this :

scroll view constraints

After setting constraints, you will notice there's red lines and errors because Auto Layout don't know the scrollable content size of the scroll view yet. No worries on this as we are going to put a view inside it next.

Step 2 : Put a view inside the scroll view and set constraints

To simplify the height calculation of the scroll content area, add a view inside the scrollview , and add four constraints (leading, trailing, top and bottom, set it to 0) from the view to the scrollview's content layout guide.


Select the view inside scrollview, press and hold control and drag it to the content layout guide.


Then in the constraints selection popup, hold shift to select multiple constraints, select leading / top / trailing / bottom constraint.

select four edges

After creating these constraints, edit their constant values to 0, so that the view will be pinned to the leading/top/trailing/bottom edges of the content layout guide :

edit constraints to zero

Let's name this view as 'Content View' as this view contains UI elements (content) for the scrollview. Auto Layout will use the content view's' width and height to calculate the scrollable area width / height for the scrollview.

After changing the four constraints value to 0 , you can notice that the red lines are still there. This is because despite pinning the edge of the view to content layout guide, Auto Layout still doesn't know what is the width and height of the view.

content view red lines

As we want to make the scrollview scroll only vertically (it does not scroll horizontally), the scrollable content area width should be equal or lesser than the scrollview size width. Next, we will create an equal width constraint between the view and the scrollview's frame layout guide, so the scrollable content area has the same width with the scrollview.

equal width

Xcode might create a proportional width constraint for you, if thats the case, edit the 'proportional width' constraint multiplier value to "1" so that it will be equal width.

equal one

Now that we have defined the width for the scrollable content area (content layout guide), what's left now is the height of the scrollable content area.

red line height

We will set an explicit height constraint value to the content view for now. We will remove it later once we have finished placing elements in it as we want to make the scrollview have dynamic height, based on the content inside it (retrieved from API etc).

Let's set the height for the content view (the view inside scrollview) to 1000 :

1000 height

Now we have set the width and height for the view, and Auto Layout can calculate the scrollable content area size, yay! We will remove the explicit height constraint (1000 pt) after finish adding UI elements.

You can scroll the scrollview in the Storyboard / Interface builder! Select the view inside scrollview in Document Outline, then scroll using your mouse or trackpad, you can see the view move.

scroll it

If you don't want to keep scrolling and want to see the whole scrollable content area, you can elongate the view controller height by setting it to freeform with bigger height like this :

freeform height
  1. Select the view controller
  2. Select "Size Inspector"
  3. For "Simulated Size", select "Freeform"
  4. Set "1100" as its height

You should see the view controller elongated to 1100 pt height now. Now you can start placing labels, images etc inside the content view (the view inside scrollview). After placing, be sure to create constraints from the top element to the bottom. You can increase the height of view controller in simulated size and height constraint of the content view as you need.

We will go into detail on how to create constraints from top to bottom inside the content view in the next section.

Here's how it looks like after placing labels and image inside the content view in scrollview:

scroll view interface builder

You can start placing elements inside the content view like label, images ,etc. Then add constraints for them so that Auto Layout can calculate their X position, Y position, width and height (can skip width and height if they have intrinsic content size). Remember that the constraints should be between each UI elements and the content view (ie. the view inside scrollview), not with the scrollview.

Your constraints might look like this:


Remember to set enough constraints so that Auto Layout can calculate the scrollable content height after removing the explicit height.

constraint explanation

The important note is that the vertical constraints must be connected from the top edge of content view to the bottom edge of content view, this is to ensure Auto Layout can calculate the scrollable content area height.

Now remove the explicit height constraint set on the content view, you should get all blue lines if you have set the constraints correctly.

After setting up constraints, you can create outlet for the labels and set the text value to the JSON value gotten from web API. Your scrollable content area height will expand based on the intrinsic content size of the labels.

This article is an excerpt from the book Making Sense of Auto Layout , if you feel like you have no idea what you are doing when adding / removing / editing constraints,  give the sample chapter a try!

Download the sample scroll view project
Not sure if you are doing it right on the scroll view layout?

Download the sample project and compare it yourself!

Tired of fighting with Auto Layout constraints? Why is it so hard to make a layout to work?! Would using code for UI and constraints make it easier? (No, not really)

If you want to understand Auto Layout fundamentally (instead of just following youtube tutorials implementing a very specific layout which might not apply to your app), check out my book Making Sense of Auto Layout, with practical case study!


“It helped me understand how Auto Layout works fundamentally - something that I couldn’t find in any tutorial. I realized what Auto Layout needs for each view to render it correctly” – Ostik Lebyak
  1. Angels in my kitchen
  2. Vintage amplifiers for sale
  3. Touch screen multimeter


next →← prev

In iOS applications, sometimes, we may need to show the content that doesn't fit into the screen. To show this type of content, we use ScrollView in the application. A ScrollView allows the user to drag the area of the content. It is an instance of the UIScrollView class, which inherits UIView.

The ScrollView allows the scrolling and zooming of its contained views. The tableview and collectionview are the subclasses of UIScrollView, and therefore, these classes provide a great way to display the content that is larger than the screen. In iOS applications, we use tableview to display the vertically scrollable content, and the collectionview to display the horizontally scrollable content.

The origin of the UIScrollView object is adjustable over the content view. A ScrollView tracks the movement of the fingers and adjusts its origin accordingly.

Adding ScrollView to the interface

Adding ScrollView to the interface builder is a bit complex as compare to the other objects. We need to define the auto-layout rules to guide the layout and position of the scroll view on the different screen devices.

Follow the following steps to add the scrollview to the interface using the interface builder (main.storyboard).

  • Search for the ScrollView on the main.storyboard and drag the result to the ViewController.
iOS ScrollView
  • Define the Auto layout rules (constraints) for the ScrollView, as shown in the following image.
iOS ScrollView
  • Add ContentView to the ScrollView and define the auto-layout rules for the content view.
iOS ScrollView

Give the constraint margin 0 to the contentView from ScrollView. We also need to make the height and width of them equal.

iOS ScrollView

Make the priority of the ContentView to the low, as shown in the below image. This is the most important step in this setup; otherwise, the scrollview doesn't scroll.

iOS ScrollView

We will have the ScrollView and the ContentView on the storyboard. Since ScrollView works when the content size doesn't fit into the entire screen of the iPhone Screen. We define the size of the ViewController screen into the size inspector in XCode. By default, the simulated size of then ViewController is fixed. However, we need to make it freeform and give the height anything greater than the current Screen height as given in the below image.

iOS ScrollView

Add a UILabel to the top, center, and bottom of the ScrollView and give the vertical spacing between them, to test whether the ScrollView is working or not. After adding the UILabels and changing the background color, the interface builder will be looking like the following window.

iOS ScrollView

The above setup will make the ScrollView to Scroll to show the whole content on the screen.

iOS ScrollView

ScrollView Properties

The UIScrollView class contains the following properties.

1DelegateUIScrollViewDelegateIt is the delegate of the ScrollView object.
2contentSizeCGSizeIt represents the size of the content view.
3contentOffsetCGPointIt represents the point at which the origin of the contentview is offset from the origin of ScrollView.
4adjustedContentOffsetUIEdgeInsetsIt represents the insets from the content inset and the safe area of the scroll view.
5frameLayoutGuideUILayoutGuideThe layout guide based on the untransformed frame rectangle of the scroll view.
6contentLayoutGuideUILayoutGuideThe layout guide based on the untranslated content rectangle of the scroll view.
7isScrollEnabledBoolIt represents the boolean value that tells whether the scroll view is enabled or not.
8isDirectionLockEnabledBoolIt represents the boolean value that tells whether the scroll view can be scrolled in a particular direction.
9isPagingEnabledBoolIt is a boolean value that represents whether then paging is enabled in a particular direction.
10scrollsToTopBoolIt is a boolean value that controls whether the scroll to top gesture is enabled or not.
11bouncesBoolIt is a boolean value that represents whether the scroll view bounces over the edge of the content.
12alwaysBounceVerticalBoolIt is a boolean value that represents whether bouncing always occurs when vertical scrolling reaches the end of the content.
13alwaysBounceHorizontalBoolIt is a boolean value that represents whether the bouncing always occurs when horizontal scrolling reaches the end of the content.
14isTrackingBoolIt is a boolean value that represents whether the user touches the content to initiate scrolling
15isDraggingBoolIt is a boolean value that represents whether the user has begun scrolling the content.
16isDeceleratingBoolIt is a boolean value whether the content was moving in the scrollview when the user stopped dragging or lifted its finger.
17decelerationRateUIScrollView.DelcelerationRateIt is a floating-point value that determines the rate of deceleration after the user lifts their finger.
18indicatorStyleUIScrollView.IndicatorStyleIt represents the style of the scroll indicators.
19showsHorizontalScrollsIndicatorBoolIt is a boolean value that represents whether the horizontal scroll indicator is visible or not.
20showsVerticalScrollIndicatorBoolIt is a boolean value that represents whether the vertical scroll indicator is visible or not.
21refreshControlUIRefreshControlIt represents the refresh control associated with the scroll view.
22canCancelContentTouchesBoolIt is a boolean value that controls.
23delayContentTouchesBoolIt is a boolean value that reprents whether the scroll view delays the handling of touch-down gestures.
24directionPressGestureRecognizerUIGestureRecognizerThe underlying gesture recognizer for directional button presses.
25panGestureRecognizerUIPanGestureRecongnizerThe underlying gesture recognizer for pan gestures.
26pinchGestureRecognizerUIPinchGestureRecognizerThe underlying gesture recognizer for pinch gestures.
27zoomScaleCGFloatIt is a floating-point value that scales the zooming of the content of the scroll view.
28maximumZoomScaleCGFloatIt is a maximum floating-point value that can be applied to the zooming of the content of the scroll view.
29minimumZoomScaleCGFloatIt is the minimum floating-point value that can be applied to the zooming of the content of the scroll view.
30isZoomBouncingBoolIt is a boolean value that represents whether the zooming has exceeded the associated scaling limits.
31isZoomingBoolIt is a boolean value that represents whether the content view is currently zooming or not.
32bouncesZoomBoolIt is a boolean value that represents whether the scroll view animates the content scaling when the scaling exceeds the maximum or minimum limits.


This is a simple example in which we will create a ScrollView and the ContentView. We will create two UIViews inside the scroll view to display the actual content.

Interface Builder

In this example, we will use the scrollview, which contains a content view. The content view will be scrolled to display two uiviews. For this purpose, use the instructions given in this tutorial to add the scrollview to the interface builder and add the scrollview to the interface.

Add the UIView to the ScrollView and define the auto-layout rules for the UIView. After adding the UIView (ContentView) to the scrollview, we need to add two UIViews and a UIButton to the storyboard.

To make the ScrollView, scrollable, we need to change the ViewController size from fixed to freeform and define some vertical spacing among the views.

Set up the auto-layout rules for the ScrollView, ContentView, UIviews, and the submit button.

AutoLayout Rules for ScrollView

iOS ScrollView

AutoLayout rules for ContentView

iOS ScrollView

AutoLayout rules for AdminDetailsView

iOS ScrollView

AutoLayout Rules for UserDetailView

iOS ScrollView


iOS ScrollView



iOS ScrollView

Click Here to Download Project

Next TopiciOS: ActivityIndicatorView

← prevnext →

Swift 4 \u0026 Xcode 11 :- Dynamic ScrollView in iOS Hindi.

Scroll View Guide

Edit PagePage History


Scroll views allow you to display content in an area on the screen that is smaller than the size of the content. They allow the user to pan (scroll) and/or zoom the content. The and are a subclasses of , so many of the points below will apply to them as well.

Basic Usage

Step 1: Add scroll view to view hierarchy

Add a scroll view to your view controller by dragging one from the Object Library. The size of the scroll view is the size of the area that is visible to the user.

Step 2: Set content size

Tell the scroll view about the size of your content area by setting the property. In this example the content has the same width as the scroll view and three times its height. The user will have to scroll vertically to access the lower parts of the content area.

Step 3. Add content subviews

What is shown in the scrollable content area of a scroll view is determined by its subviews. The frame of each subview is relative to the top left of the content area. A scroll view can contain more than one subview. In this example we add a series differently-colored subviews. Each subview has the same width as the scroll view, but we offset the top of their frames so they do not overlap each other.

Here's what our example looks like when running:

Scrolling programatically

Set content offset

You can programatically scroll the contents a scroll view by setting its property.

Scrolling to a subview

If you want to make sure a given view is visible on screen you can you can use the method.

Using paging mode

Enabling paging

You can force the scroll view to to snap to "page" boundaries by setting the property. The size of a page is equal to the size of the scroll view. You'll generally want to disable to scroll indicators when paging is enabled. Here we allow the user to horizontally page through three views.

Adding a page control

The paging behavior is often combined with a that displays a dot for each page and allows the user to switch pages by tapping. This behavior can be achieved by implementing the and adding an action handler for the page control.

Pinch to zoom

Basic zooming behavior via pinch gestures is provided by the scroll view if you implement the delegate method. Since a scroll view can have more than one subview, this method will identify which view will be zoomed when the pinch gesture fires. You'll also need to set the and .

Using scroll views with auto layout

As noted above, there are two sizes that are relevant when working with a scroll view:

  1. the scroll view's (frame) size. This determines how the scroll view fits inside its parent view and its size as it appears on the screen to the user.
  2. the scroll view's content size. This determines the size of available to the scrollable content within the scroll view.

In order to use a scroll view with auto layout you must still specify both of these sizes.

One approach to accomplishing this is to use auto layout constraints only to determine the scroll view's size relative to its parents and neighbors. The content size and size of subviews inside the scroll view are still set programatically as we have been doing throughout this guide.

A second approach uses only Auto Layout constraints. In particular, this means there must be a way for Auto Layout to specify the content size of a scroll view. Altogether, the constraints must be enough to determine three things:

  1. The size of the scroll view. You can use the pin and align tools to create constraints to parent and sibling views. Unlike other views, you cannot rely on the size of child views of the scroll view here.
  2. The content size of the scroll view. This is specified by creating constraints between the scroll view's edges and the subviews within the scroll view. Note that these constraints have a different meaning than normal constraints between a parent view and its child views. The only size being determined here is the content size of the scroll view.
  3. Finally you must set constraints to determine the size of the actual subviews containing the scrollable content. These constraints cannot depend on the edges of the scroll view—since as we just saw, they would then be interpreted as constraints on the content size. It is typical here to set a fixed size for a single main scrollable subview and to place other views inside this subview.

A comprehensive discussion of this topic can be found here.


Ios scrollview

About a week later, I left my office early and met her after work, went to see her off, it took a long. Time to walk, we walked and talked. At the end of the walk she asked: - Vasya, can I ask you one question. - Ask. - I know that you have a wife, a child.

SwiftUI Bootcamp #15: How to use ScrollView

For example, Masha Palkina fucked in a sanatorium with a health resort, with a customer's representative in a hotel, with a boss at work. If Masha's sex with the customer's representative and the boss Vanya Palkin did not approve of it, but admitted its expediency, then he did not like the story with the holiday-maker. At all.

The fact is that the health resort traveler, as soon as he met Masha, immediately threw her into sex, and tore her up from.

You will also be interested:

He went out onto the porch and began to count the harvesters passing by. For some reason, he did not count longer than one. He drove from side to side until he died out in the distance, near the river.

801 802 803 804 805