How can add Auto Layout constraints programmatically to center a view in the remaining space (see example picture below)?
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.