Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScrollView Causing "Misplaced Views" AutoLayout issues

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):

Properly functioning constraints for the UILabel

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:

UITextField constraints causing Misplaced Views issue

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.

like image 771
Mike Z Avatar asked Jan 10 '23 07:01

Mike Z


1 Answers

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:

  1. 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.

  2. 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.

like image 168
vacawama Avatar answered Jan 21 '23 11:01

vacawama