Auto Layout centering view in remaining space (programmatically)

前端 未结 2 1718
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题