2
votes

Using the storyboard and auto-layout I drag a scroll view into the view controller and satisfy auto-layout constraints appropriately. I add in a Label centred on the screen with the appropriate auto-layout constraints.

Implemented the following code in viewDidLoad, viewWillAppear and viewDidLayoutSubviews (at different run times of course)

scrollView.contentSize.height = 1000

When running in the simulator the view only scrolls horizontally not vertically. It didn't make sense at first when seeing it scroll horizontally without applying specific conditions to do so, until i looked closely into the constraints.

When initially dragging in a UIScrollView and selecting the Pin option to add constraints it shows the leading and trailing space to have a default value of -20 instead of 0. This seems to explain the automatic horizontal scrolling but still does not explain why I am not able to implement vertical scrolling.

I have also tried specifying the content size using CGSize:

scrollView.contentSize = CGSize(400, 1000)

or

scrollView.contentSize = CGSize(view.frame.width, 1000)

neither seem to work. I also implemented the above methods with the same parameters using the initialiser CGSizeMake(width, height) and also does not work.

Scrolling is checked as enabled as are other options as per default when selecting a scroll view.

1
You should show us the constraints for your label. - beyowulf
at first read of your comment i thought the relevance of the labels constraints isn't important but got me thinking and i simply removed the label leaving only the scroll view and it now scrolls as intended. Can't believe it was the label holding the view back. Sorry for such a rookie mistake, appreciate the eye opener @beyowulf - Vince
@beyowulf my constraints were leading, trailing, bottom and top spacing to superview (Scroll View). Suggestions as to what the constraints should be to remove its control of preventing the view from scrolling vertically ? - Vince

1 Answers

3
votes

You can set the constraints to centered horizontally and vertically in container view. This has the unfortunate effect of raising an error "Scroll view has ambiguous content size." If you know for a fact you're going to set the content size in code, you can ignore it.

But it's probably a better practice to drag out an empty UIView call it containerView, pin it top/bottom/left/right to the scroll view center the label like above. Set a constraint for the containerView's height. Then create an IBOutlet for the height constraint of the containerView call it containerViewHeightConstraint. Then in code say:

self.containerViewHeightConstraint.constant = 1000 //or whatever height you want for scrolling