iOS UIScrollView with autolayout not centering cor

2019-09-17 02:52发布

问题:

After googling and searching for a solution to this I have decided just to ask a question.

I am trying to setup a UIScrollView with AutoLayout being left on. I have been researching this all day and finally got the ScrollView to behave correctly with AutoLayout by putting a child view inside of it and then all of the subviews inside of that.

I set up the constraints in the Scroll View to 0 on all 4 sides, same with the ContentView (subview of ScrollView) and then set the ContentView and the parent view of the ScrollView to equal widths.

I then added 2 labels into the ContentView and set them to be horizontally centered and added the correct constraints to get rid of the ScrollView ambiguity.

The labels are in the correct spots vertically, but are off screen horizontally on an iPhone 5s.

Here are the constraints:

Here is what it looks like in preview:

But here is what it looks like in the simulator:

Any ideas as to why this is happening?

Thanks in advance!

EDIT After removing the equal width constraints, the view is finally showing up but the labels are off center:

EDIT 2 Screenshot of storyboard with UILabel constraints.

回答1:

OK. So I think I lead you astray with my initial comment about the equal widths constraint - that is needed to stop the content view from expanding and taking your labels with it.

I am still not sure why it was collapsing to zero though.

Take a look at this SO question which seems to cover a similar issue. Do your constraints match theirs?

Edit - actually this answer may be clearer.