How can add Auto Layout constraints programmatically to center a view in the remaining space (see example picture below)?
For the moment, I add a container view at the bottom and I then center the view in the container view, but I was wondering if there was any other solution without needing to use a container view.
You need to add a spacer view to do this.
Let's start with 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:
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:
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:
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:
Now I'm ready to set up the blue view. First I'll give it a fixed size:
Second I'll center it horizontally in the root view:
Third I'll pin its vertical center to the spacer's vertical center:
That's all the constraints I need. I'll update all frames to check:
I can test it out using Preview in the assistant editor:
Notice that the spacer view isn't visible in the preview, but still participates in layout.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With