0

I have 4 UIViews in my UIViewController with colours: Yellow, Green, Grey and Blue.
I also gave the following auto layout constraints:
Yellow view: Top-8-superview, Leading-8-superview, Trailing-8-superview, height = 120
Green View: Top-8-YellowView, Leading-8-superview, width=200, height=100
Grey View:Top-8-GreenView, Leading-8-superview, Trailing-8-superview, bottom-8-blueView;
BlueView: Bottom-60-superview, trailing-8-superview, width=260, heigth=30
After compile and run, it looks like this:

enter image description here

At this point, no problem, no constraint complaints, everything is fine.

However, I changed the 4 UIViews' parent view to UIScrollView, and then the UI display wrongly: only green view displays correctly, yellow view and grey view are missing, blue view shows a small part. enter image description here

In the console I checked that the scrollView's contentSize.width is 16, which is incorrect, so I tried to correct it in viewDidLayoutSubviews:

self.scrollView.contentSize = self.view.bonds.size;
[self.scrollView setNeedsDisplay];
[self.scrollView layoutIfNeeded];

The contentSize becomes (414, 736), which is correct, but the display is still same as my second attached image. I listed out the view details:
YellowView: frame:(8, 28, 0,120)
GreenView: frame:(8, 156, 200,120)
GreyView: frame:(8, 264, 0, 274)
BlueView: frame:(-252, 646, 260,30)

What I observe is, if I give a width constant, the view is at least has width greater than 0, and for the Yellow and Grey view, since they are blank view with no width constrains, they will have problem to show.

What is the best solution to fix it other than give width constraints? I am also wondering why the width of yellow and grey is zero, since I also gave top, leading, trailing, height constraints?

1 Answer 1

1

Add contentView as subview of scrollView and then all your subviews as subviews of contentView. Constraints for contentView set as width = superview.width, height >= superview.height and pin 4 sides of contentView to scrollView (leading, top, trailing, bottom). More info: https://www.natashatherobot.com/ios-autolayout-scrollview/

Sign up to request clarification or add additional context in comments.

1 Comment

Now it's working. Thank you Timur. It basically need to set mainview-scrollview-contentView with constrains.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.