Resize Uiview with Auto Layout

后端 未结 1 1482
抹茶落季
抹茶落季 2021-02-09 04:01

Right now I\'m studying auto layout and I\'m facing a problem that I can\'t solve.

I have a view that loads correctly in a 4 inch device (left view) and I\'m trying to a

相关标签:
1条回答
  • 2021-02-09 04:50

    You need equal-height constraints between the green and black views, and between the orange and pink views.

    Let's construct your layout from scratch. It's usually easier to set up constraints if you make your views smaller than you want, and edit the constraint constants to size them up. So we start with five views:

    five views no constraints

    This layout of the views here is important! Note that the orange view, for example, is strictly to the right of the green view. This means if I ask Xcode to create a constraint from the green view's trailing edge to its nearest neighbor, that neighbor is the orange view, not the superview.

    It is helpful to name the views in the document outline. To name one, click its entry in the outline, press return, then type the name:

    names in outline

    Select Blue. Give it constraints with constant 0 on the top, leading, and trailing edges, and a height constraint:

    blue constraints

    If you update its frame (as I did in the dialog), Xcode will lay it out like this:

    blue laid out

    Next, select Green. Give it constraints with constant 0 on all four edges. Top should go to Blue, leading should go to superview, trailing should go to Orange, and bottom should go to Black. You can check which view is on the other end of the constraint by clicking the disclosure triangle:

    green constraints dialog

    Don't update Green's frame yet! It should look like this:

    green constraints

    Next, do the same for Orange, Black, and Pink.

    Once you've created the edge constraints for all four of the bottom views, select all four of those views (Green, Orange, Black, and Pink). It should look like this:

    constraints on bottom views

    With all four selected, create equal-width and equal-height constraints:

    equal width/height dialog

    Note that this is overkill. We don't really need the equal-height constraints between the left and right columns, and we don't need the equal-width constraints between the top and bottom rows. But this answer is already a mile long and it's much shorter to create all the equal-size constraints in one action.

    Now it should look even messier:

    messy

    Select the top-level view or the view controller and choose Update All Frames in View Controller:

    update menu item

    Xcode should lay out the views like this:

    good layout 4 inch

    If you click the form factor toggle button, Xcode should lay out the views like this:

    good layout 3.5 inch

    I've uploaded the final storyboard to this gist.

    0 讨论(0)
提交回复
热议问题