• Ashley Ng

ScrollViews, AutoLayout, dynamic content, oh my!

Have you ever wanted to display a lot of content in a ScrollView? Have you also needed that content to be dynamic? Well you're in the right place! I struggled with this (for longer than I care to admin) a few days ago, but most of the tutorials and StackOverflow questions were either just for images, or not really dynamic content, or they just suggested TextViews (which wasn't what I needed). In short, the trick is that the UI elements in the scroll view need to have a height (or intrinsic height).

1. Add a ScrollView to your ViewController and pin it to the edges of the parent view, you generally want this to be 0 all the way around.

2. Add a UIView (thus referred to as the ContentView) inside the ScrollView and pin it to the edges of the parent view as well. If you are using the Safe Area Layout, make sure the ContentView is pinned to the SuperView and not the Safe Area. Note there is an error because there is no content in our ContentView and the ScrollView is complaining that it needs a Y position or height. Not to worry, we will be adding content to our view and this will go away!

3. If you want a vertical scroll, make the ContentView the same width as the parent UIView (NOT THE SCOLLVIEW). If you want to have a horizontal scroll, you make it the same height instead. In the my example app for the horizontal scroll, I did the same height as the Safe Area because of the added TabView at the bottom.

4. Add the UI elements you want into the ContentView. In my case, I add a UILabel, UIImageView, and a UIButton. Make sure if you want to display a lot of content in the UILabel that you set `Lines` to 0 so that it can display as many lines of text as it needs.

5. Pin those UI elements however you like to the edges and however you want the spacing to be between them. Don't currently worry about any of the element's height.

6. Now if you added the same elements as I did, you should still have an error that the ScrollView needs a Y position or height. This is because the ImageView doesn't have an intrinsic height. If you removed it (and redo the constraints so that the label and button have a constraint between one another), you shouldn't see the error any more. But I go ahead and set the ImageView height to 256 and aspect ratio of 1:1.

7. Final step is to actually hook up all those elements to show some data. I'm not going to go step by step for this since it's not the topic of the post, but you can look at the GitHub repository for the project if you need help.

This should be a good starting off point for your own app if you're needing something similar (or if it's exactly what you needed, lucky you!).

Happy Coding. Happy Growing.

12 views0 comments

Recent Posts

See All