A benefit of working with UITableViewControllers is the built-in ability to scroll when the content is longer than the screen. Sadly, this functionality doesn’t come standard for all Views. This is where Scroll View comes in to save the day. Unfortunately, it’s not as simple as just dragging a Scroll View onto your View Controller. There are a few more steps involved to get it working. I’ve broken it out into 12 easy steps to get your Scroll View up and scrolling!
- First up, add a Scroll View to your View Controller.
- Drag the four corners to the edges of the view.
- Add new constraints setting each to 0 as shown below. Make sure Constrain to Margins is unchecked.
Don’t fret when the lines around your view controller turn red, we are just getting started.
4. Add a Vertical Stack View inside the Scroll View.
5. Drag the four corners to the edges of the View Controller.
The beauty of a stack view is that if a height and width aren’t set, its size is based on its subviews so it will expand or contract to fit the content inside.
6. Hold down control and click on Stack View and drag to Content Layout Guide. When the menu pops up, hold down shift and click on Leading Space, Top Space, Trailing Space and Bottom Space to Content Layout Guide.
7. Just below the Stack View, click on Constraints to make sure the four constraints are set to 0. For some reason, some of the constraints sometimes get set to something other than 0. Click on on them and in the Size Inspector and change the Constant to 0.
8. Next, hold down control and click on Stack View and drag to Frame Layout Guide and select Equal Widths.
** Content Layout Guide and Frame Layout Guide are new in Xcode 11.
We are almost there!
9. Click on View Controller and go to the Size Inspector to change the Simulated Size from Fixed to Freeform and put in a height of 1000.
This will make your view controller longer in the storyboard so you can add your content that would normally be cut off it was longer than the actual screen size.
10. Add a UIView inside the Stack View.
11. Drag the edges out to fit the view controller.
12. Set the constraints to 0 on all sides and add a height of 1000.
** The height size of 1000 is not set in stone. You can set the height of your View and the View Controller’s Simulated Size from step 9 to fit your content.
All the layout issue warnings and errors will disappear and you are ready to add your content to the View.