BabyAzerty BabyAzerty - 2 months ago 27
iOS Question

Missing constraint x and height to UIScrollView in autolayout

Disclaimer: I saw a SO technique which includes adding an UIView (being called a contentView) to the UIScrollView and putting everything to this contentView. I don't want to use this technique as I would like to understand why I am having the current problem.

I have a UIScrollView on the default UIView of a UIViewController, its UIScrollView has 4 constraints: One on each side (trailing, top, leading, bottom) so that it glues to its parent the UIView.
This works!

Working UIScrollView constraints

But when I want to add an UIImageView to the UIScrollView and I want it to be glued to its parent sides (trailing, top, leading) + a specific height, now I have a problem.

Non working UIImageView constraints

It says:

Scroll View: Has ambiguous scrollable height
Scroll View: Needs constraints for: X position or width


The reason xcode throws those error is because it cannot calculate UIScrollView and UIImageView frame in the runtime.

when you add constraint for UIScrollView related to its superview, it tells xcode to draw scroll view as big as its superview. However, when you add constraint for UIImageView related to UIScrollView size, it tells xcode to draw image view as big as UIScrollView content size. please note that UIScrollView size and content size is two different thing.

if we think of it as a house, scroll view size is basically window size, it is a size that you can use to see the inside of the house. And content size is the size of the house. which is why there is no relation between scroll view's size and content size.

you can fix your problem in two ways, first by set scroll view content size either programmatically or by using IB. Although, I'm not sure if setting it programmatically will silence the warning. You can set it in IB by following the answer here. second ways involving adding more constraint to your UIImageView. By adding bottom constraint and width constraint, xcode can calculate UIScrollView content size which will remove this warning.