Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 356
Kalzem Avatar asked Nov 22 '15 21:11

Kalzem


2 Answers

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.

like image 142
seto nugroho Avatar answered Sep 19 '22 15:09

seto nugroho


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.

like image 35
Raxak Avatar answered Sep 21 '22 15:09

Raxak