jo3birdtalk
jo3birdtalk

Reputation: 616

Working with UIScrollViews

I've watched many Youtube videos on UIScrollView. Here, here and here. However nothing there is solving my issue.

Here I've a sample storyboard that I'm working with.

enter image description here

What I require:

  1. The ViewController must be embedded in a Navigation Controller.
  2. BlueView and CyanView will adjust its height accordingly to screen size based on aspect ratio.
  3. YellowView will have a variable height as it contains a ContainerView with embedded UITableView or UICollectionView. Meaning my users can switch between views to look at similar data, with different format. Its information is grabbed from server side. This means that if there is no content, it doesn't require any scrolling. If there are many rows of data to fetch, scrolling should work to display all my information.

Problem faced

  1. If I do not set specific heights to each of my views, IB will complain about the need for constraints on height or Y position.
  2. When I try specifying the height in IB (so as to avoid the complain), during runtime, I attempt to change the height of my yellowView and myScrollView, the scrolling doesn't happen at all.

Upvotes: 1

Views: 52

Answers (1)

Rikh
Rikh

Reputation: 4222

Inside the UIScrollView add a container View. That will contain rest of your views. So the heirarchy becomes like this:

|---UIScrollView
       |----UIView
               |---Blue View
               |---Cyan View
               |---Yellow View

This container view will have a leading, trailing and bottom and top to the UIScrollView. Also add a equal width and equal height constraint to your UIViewControllers main view. Give a priority of 250 to the equal height constraint. And then:

  • To the blue view, add a leading, trailing and top constraint to its superView and add the aspect ratio constraint. Tinker with the values till you see a UIView which looks nice to you.
  • To the cyan view, add a leading and trailing to its superView and add a top spacing to the blue view. Add the same aspect ratio as the blue view.
  • Now for your yellow view, add a top to the cyan view, and leading, trailing and bottom spacing to its superView.

Now your UITableView will have a leading, trailing, bottom and top to the container view or just directly use a UITableView.

If you wish to embed a UITableView inside the yellow view or just use a UITableView directly and expect the main UIScrollView to be scrollable, you will have to manually get a height constraint outlet for your UITableView and update it accordingly depending on the number of rows of the UITableView and height of each row so that the yellow view can increase its height based on the height of the embedded UITableView and hence update the content view accordingly which will in turn update the total content size of the UIScrollView.

Upvotes: 1

Related Questions