7
votes

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
3

3 Answers

8
votes

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.

3
votes

To solve this issue, I did the following thing: 1. Inserted a scrollview. Gave it constraints to Superview from all directions 2. Inside Scrollview, I added an another UIView.Then, I added similar constraints to Superview from all directions to the UIView as well. In addition to this, I gave it Vertically center alignment and Horizontally center Alignment. This removed the constraints errors.

0
votes

This worked for me.

Do the following in your storyborad

  • Add a hidden view of height placed at 0,0 in your scrollview.
  • Add constraints to the hidden view , top = 0 , left = 0, right = 0, bottom = 0.
  • Add the constraint on this hidden view to make it center aling horizontally to the scroll view.

This should take care of the scrollview complaining about the x position.