I'm running into a strange AutoLayout related issue when I use a UIScrollView
(the issue does not occur without it).
I have a UIScrollView
that is constrained to the boundaries of a UIView
(contained within a UIViewController
), and within that, I am attempting to place a UILabel
and UITextField
side by side. I have constrained the UILabel
to the left and upper boundaries, with it's width and height constrained (see screenshot below):
Right next to this UILabel
is a UITextField
, which is constrained to the left, top, and right, as well as having the height constrained. However, this results in a "Misplaced Views" warning, that states "Expected width = 163
, Actual width = 413
", shown in the screenshot below:
When I choose to "Reset to Suggested Constraints", the "Misplaced Views" issue disappears, but in it's place I am left with a width
constraint of 413 points, which is something I'm hoping to avoid, as I would not like this UIViewController
to be horizontally scrollable on smaller devices.
A scroll view has a size (the size it takes up on the screen) and a content size (the size of the entire scrollable area). In Auto Layout, the content size is automatically computed from the constraints of the items in the scroll view. This is a problem, because you are trying to make the scroll view have the same width as your screen, and then have the items constrained to that. When you do that, Auto Layout insists that you give your text field an explicit width so that it can calculate the width of your scrollable area.
To do what you want, do the following:
Add a "content view" to your scroll view. This view will be the only top level item in your scroll view. It will hold all of your content as subviews of it. Drag out a UIView
and add it to your scroll view. Constrain its top, leading, bottom, and trailing edges to the scroll view. Constrain its width to the width of the scroll view. Give it a height constraint and set it however big you want your content area to be.
Add all of your labels and textfields to this content view. Now you can constrain them centered in your content view or constrained to the edges, and it will work as you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With