#23 UIScrollView layout programming/coding without storyboard

Stephen Huang
2 min readFeb 1, 2022

How to set contents that can make a UIScrollView’s scroll area autoresizing.

A UIScrollView consists of

  1. a content layout guide
  2. a frame layout guide

Frame layout is what size that UIScrollView show on the view.

Content layout is that scroll area really size.

  • Create UIScrollView
var testScrollView: UIScrollView = {var scrollView = UIScrollView()scrollView.translatesAutoresizingMaskIntoConstraints = falsereturn scrollView}()
  • set Constraint — this is frame layout guide
testScrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = truetestScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = truetestScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = truetestScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
  • content layout guide
testScrollView.contentLayoutGuide.owningView?.topAnchor.constraint(equalTo: view.topAnchor).isActive = truetestScrollView.contentLayoutGuide.owningView?.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = truetestScrollView.contentLayoutGuide.owningView?.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = truetestScrollView.contentLayoutGuide.owningView?.bottomAnchor.constraint(equalTo: (The last component).bottomAnchor).isActive = true

if set by this, testScrollView’s scroll area will follow the last component’s bottomAnchor.

— — — — — — — — — — — — — — — — — — — — — — — —

If you want to use UIScrollView by storyboard.

And you are wondering how to set UIScrollView’s content.

You can watch the url down here.

If you want to set contents without storyboard.

I will talk about it now.

First, if you never use layout programming before.

You need to watch the article here.

Photo by AltumCode on Unsplash

--

--