Reputation: 691
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.
Upvotes: 2
Views: 1010
Reputation: 15321
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
Upvotes: 3