Auto Layout centering view in remaining space (programmatically)

前端 未结 2 1722
無奈伤痛
無奈伤痛 2021-02-04 00:29

How can add Auto Layout constraints programmatically to center a view in the remaining space (see example picture below)?

相关标签:
2条回答
  • 2021-02-04 01:07

    The accepted answer doesn't address the programmatic alternative (which you emphasized in your question).

    There is a programmatic way to do this without having to add additional dummy views to the view hierarchy using UILayoutGuide which was introduced in iOS 9.

    The documentation for UILayoutGuide is detailed enough.

    This article also add more explanation (Here is the updated code from the article).

    0 讨论(0)
  • 2021-02-04 01:21

    You need to add a spacer view to do this.

    Let's start with some views:

    some views

    I'll set up the pink view to take up the top 70% of the root view. First I pin it to all four edges of the root view:

    pink constraints

    Then I'll edit the bottom constraint in two ways. First, I make sure the first item is the pink view, and second I set the multiplier of 0.7. Then I update the pink view's frame:

    pink constraints adjusted

    Next I'll add the spacer view. I don't want the spacer view to be visible at runtime, so I'll make it hidden. Hidden views still participate in layout. Before setting up constraints, I just put the spacer to the left of the blue view:

    spacer added

    Now I'll create constraints to make the spacer stretch from the bottom of the pink view to the bottom of the root view. The width doesn't matter so I'll just pin it to the left edge of the superview and make it thin:

    spacer constraints

    Now I'm ready to set up the blue view. First I'll give it a fixed size:

    blue size constraints

    Second I'll center it horizontally in the root view:

    blue horizontal center

    Third I'll pin its vertical center to the spacer's vertical center:

    blue vertical center

    That's all the constraints I need. I'll update all frames to check:

    update all frames

    I can test it out using Preview in the assistant editor:

    previews

    Notice that the spacer view isn't visible in the preview, but still participates in layout.

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