Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Layout centering view in remaining space (programmatically)

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

enter image description here

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.

like image 965
quentinadam Avatar asked Oct 06 '14 12:10

quentinadam


2 Answers

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.

like image 181
rob mayoff Avatar answered Nov 14 '22 18:11

rob mayoff


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).

like image 26
alobaili Avatar answered Nov 14 '22 18:11

alobaili