UIScrollView with Content View

2019-07-28 18:11发布

问题:

I've been trying to create a UIScrollView for user registry but with no success. I'm using auto layout and all of the fields that go inside the scroll view are static. Because of the usual ambiguous height issue, I've added a UIView inside the scroll view, set the constraints to the margins of the scroll view and centered aligned it. After that I added all of the fields inside that Content View, in the storyboard.

The content fields have their constraints setup as you would expect, but when I get to the lowest field and set the bottom constraint to the bottom of the Content View then everything breaks.

I'm asked by Xcode to set the priority of some views, and when I do as is says, the Content View size stays the same and the views are shrunken.

I tried not to put the last bottom constraint and resize the Content View by code but the height is not resized as is should.

I'm looking for a good solution to do this in storyboards and auto layout.

Update: I added a bottom constraint with a low priority, but the content scroll view is not expanding to show all of the fields.

回答1:

You are using auto layout so the size of the content view is determined by constraints. Follow the below steps to provide proper constraints:

  1. Drag the Scroll View inside main view and provide constraints Top, Bottom, Leading and Trailing in align with Super View (Main View) as per screenshot.

  1. Take View which will contain your content and drag inside Scroll View. and provide the constraints Center X, Center Y, Top, Bottom, Leading and Trailing in align with Scroll View as per screenshot

  1. Put all the element inside content view which is a subview of scroll view and provide Top constraint relative to the element above it, to make equal space between the elements (eg. label, button etc.) (Make sure you provide required constraint for X-position)

  2. Last element is "Register Account" button make sure you provide the Top Constraint relative to country and Bottom constraint relative to superview (content view) and change the priority for Top or Bottom constraint as per screenshot, otherwise it gives error.



回答2:

  1. Add&Set ScrollView(UIScrollView)

  2. Add&Set ContentView(UIView) with subviews

! Set ContentView Width equal to View Width

  1. Set all subviews constraints
  2. View1 should be tied to the top of the ContentView

  3. View4 should be tied to the bottom of the ContentView

  4. All SubView (View1, View2, View3, View4 ...) must have a height and distance between each other

P.s. In your case, if iOS > 9.0 you can replace ContentView with UIStackView