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).
Related
Assume the following, simple layout:
Three views vertically stacked upon each other
Using simple vertical spacings between the views
Is it possible to hide the red view including its margins using constraints / AutoLayout only?
Settings redView.isHidden = true will hide the red view but will not change the position of the blue view. The blue view will stay at the same position as if the red view would be visible.
Using redView.removeFromSuperview() to completely remove the red view would show the desired result. Due to its optional spacing constraint to the gree view the blue view would move to where red view was. However it would be quite hard to re-show the red view because all its constraints would have to be set up from scratch.
In Android setting the visibility to View.INVISIBLE simply hides a view (as the first case described here) while View.GONE renders the remaining layout as if the view was not there at all.
Can this be done with iOS using constraints / AutoLayout only?
Of course I can achieve the same buy manually manipulating the constraints and setting up new constraints in code. But the question is, if there is a more convenient solution as in Android?
A VerticalStackView seems to fit your requirements. You can include all the views in the stack view and set the spacing directly on it.
Then, is one of the views is hidden, the stack view will automatically adjust all the constraints.
Take a look at the pictures:
If possible, wrap your views in a vertical UIStackView. You can then individual views and the other views will be rearranged as intended. You also don't need to add constraints between items, since the stackview handles the spacing between views.
The simplest way is to embed the views into a StackView and when one of them is hidden, the one below will move up into its place.
Follow these steps:
Add all the views you need in the storyboard/xib
Editor - Embed in stackView
Set the spacing in the stackView
Set the stackView constraints
Create outlets for the views you want to be hidden in a certain case
Set that views hidden property to true
Regarding the constraints, you can set them for the StackView and for the vertical one, just set the equal spacing and the space properties in the StackView.
Result:
I have a UIView in my UIViewController in storyboard which I want to add a constraint on to space that view a distance from the top edge.
Now, when I do the usual by ctrl + drag to the ViewController's main view I only get option to set it to top layout guide.
This is a problem for me because at one point in the app Im going to move the main view up around 20-50px and what happens then is that view I have will not move... because its not aligned to superview.
How can I manually do this in storyboard or do I have to add it programatically?
Im using xcode 6.
There is an arrow to the right of the constraint constant value. If you click on it, a menu pops out where you can choose what is it that you want to make your constraint relative to. If you choose 'View', than it will pin it to the top of the view.
You should be able to do it by highlighting the view you want in the storyboard and then selecting Editor > Pin > Top Space to Superview in the top menu.
This is outdated in XCode 7, see #PaulGurov's answer instead.
TL;DR: You can constrain to the margin by pressing the Alt key on the keyboard.
One can also add that if the view you are trying to pin is not a direct subview of the view that you want to pin it to, the suggested approach is not really valid. Let's say the view hierarchy looks like that and you want to pin the image view (Parallax Image View in this case) to the view controller's view (View in this case).
To do that you just Control + Drag from the Parallax Image View to the View. That presents the default choices where you can see Vertical Spacing to Top Layout Guide to pin the Parallax Image View to the top layout guide.
What you want is to pin it to the top (margin) of the view. To do that you have to switch to the other set of constraints by pressing Alt
I had a whole bunch of constraints already there and I just wanted to change them rather than break them. Turns out if you double click on the constraint to edit, then click on the item that has the ".Margin", you can just turn off the "Relative to Margin" by selecting that item.
Dan's answer works. I just wanted to state that if you set your view in storyBoard at y < 20, and configure constraints through the pin panel, it will set top to superview:
If the height of the view is set to 0 by accident, Vertical Space to Top Layout Guide will NOT appear. Vertical Space to Bottom Layout Guide will appear, however, which must have made sense to someone inside Apple circa 2004.
None of the above answers worked for me, instead I have to do a hack to set my subview's top with superview's top instead with Top layout guide.
First, set the subview center vertically with superview.
Then, change the Center Y constraints for subview as well as superview to Top constraint.
You are good to go now.
How to set up autolayout in Interface Builder to arrange views vertically as shown on image:
Top view pinned to top screen edge, Bottom view pinned to bottom screen edge. My view should be centered between top and bottom views (so distance to Top view equals to distance to Bottom view)
The way to do this is to have 2 invisible "spacer" views between you visible views.
You can't make spaces have equal height. But you use the "spacer" views and place them between your views (with 0 gap to the surrounding views).
Then you give these views equal heights and they will push your views around to centre the My View with equal gap to the Bottom View and Top View.
i.e. like this...
V:|[Top View][spacer1][My View][spacer2(==spacer1)][Bottom View]|
EDIT - Another way
I just thought of another way of doing this. You could have an invisible container UIView that is between Top View and Bottom View with no gap.
Then you place My View inside this invisible view and centre it vertically.
One more solution is to add an invisible view between top view and botom view and place my view in center of this view:
(5 years later) I've found the most canonical solution:
UILayoutGuide is specially introduced to solve this kind of tasks (since iOS 9).
Use layout guides to replace the dummy views you may have created to represent inter-view spaces or encapsulation in your user interface - Ref docs
It works pretty fine in code, but unfortunately Interface Builder doesn't support custom layout guides.
I have trouble implementing scrollview with auto layout:/
Here is simple "Hello World" project with that problem: http://www.sendspace.com/file/cg96by
But the problem… I need to create scrollview, but also I need to use auto layout. So I created pure single view application, added (like I saw in some tutorials) Scrollview (the same size as main view), added constraints (all zeros) and then add Container View (the same size as scroll view), add constraints and.. It's didn't work:/ It doesn't scroll. Here is the screen of that situation:
Now, when I delete two constraints named: Center X and Y Alignment (marked on the screen), it works perfectly, but Xcode5 doesn't quite like it :/ and shows some errors like on the next screen below.
Why does he want width and heigh 0 ?!
Actually ContainerView doesn't matter. I've also tried with image view. When you select "Add missing constraints" it also add Center X and Y Alignment. And scroll doesn't work. When you delete them, scroll works but you have this warring:
Ok, I find manually adding the autolayout constraints to be quite confusing, using the "Add New Constraints" button at the bottom really comes in handy, try this, after you get each view where you want it use that way of adding layout constraints for each view (ie scrollView, containerView, UIImageView) I did this, and heres the example, select each constraint as I have so that the top, left, bottom, and right edges are set, this should do exactly what you want.
You will probably want to erase all your current constraints and then implement them this way.
heres the layout like you want http://cl.ly/image/463k2043401L
and heres the example adding the constraints: http://cl.ly/image/472l2V0l3N1L
To keep it dynamic so that you can rotate it, you will want to do the above for all view BUT the container view... then If you control drag from container to scrollview with no constraints, you can add all of them that it suggests except for the height and width at the bottom, that satisfies any missing constraints and should do the trick, It will center the container inside of the scrollview and keep it pinned to the top, bottom, left and right, and it should dynamically change with your scrollview content size.
http://cl.ly/image/1o3k1e452W0g
Sorry for the confusion, hope this helps!
I had a similar problem and i found relative simple solution from within Interface Builder using pure Autolayout without any code.
For proof-of-concept at first remove any constraint in View Controller to if see this works.
This is sample layout:
View (main view of my UIViewController)
Scroll View (UIScrollView)
Container View (UIView)
Content View (e.g. UIImageView)
A. Scroll View width/height should be smaller that Container View width/height
B. Container View should have some determinated width/height (may be explicit width/height )
C. Do Control-drag Container View to Scroll View and add only:
Leading Space to Container
Trailing Space to Container
D. Check out those two constraints and set "constant" value for both to 0
E. Run app and
I am attempting to layout a screen design using constraints (auto-layout) from interface builder and hope to avoid coding constraints, but I would accept an answer for either case I guess.
I have two subviews in a contained in a top level view. I want to fix vertical distance of the first subview to the top of the screen (I was able to accomplish that - common use case for a vertical space constraint). I want the second subview to float (vertically) in the center of the distance between the bottom of first subview and the bottom of the screen. The idea is that the design responds somewhat to iPhone 3.5" vs 4" dimensions.
I am having trouble defining a constraint or set of constraints that would accomplish this.
I have tried setting inequalities on the vertical spacing constraints between the second subview and the top of it's neighbor (the first subview) and the bottom of the superview, and playing with the priorities of those constraints.
An idea that was suggested in a few other related posts on SO is to use a container that is pinned to the bottom of the screen, as well as the pinned to the bottom edge of the first subview, and then center my second subview in the container. I was hoping to avoid complicating the view hierarchy if possible, but maybe that isn't easily avoided.
Any thoughts or suggestions?
UPDATE
This answer describes how to do this in Xcode 6.0 (and probably works in Xcode 5.0 and 5.1).
ORIGINAL
If you want to do this with auto layout, you have to add at least one spacer view. It doesn't have to be the superview of the vertically-centered view (or any other view), so it has a pretty minor effect on your view hierarchy.
I recommend not trying to set up constraints in Interface Builder in Xcode 4.6.3. It's just too painful. But if you really must, this is doable.
Create a spacer (a plain old UIView) from the bottom edge of the top-hugging view to the bottom edge of superview. Set it to hidden. Give it constraints to the top-hugging view and the left and bottom edges of the root view, and pin its width. My spacer width is 10:
Add your middle view (here, a button). Give it a “Horizontal Center in Container” constraint. Then select both the middle view and the spacer view and give them a “Vertical Centers” constraint:
Note that if you drop the middle view when IB is showing the correct guidelines, it will set these constraints for you.
You can test by enabling resizing for descendents (but not siblings & ancestors) and resizing the root view in IB. The middle view will remain centered between the top-hugging view and the bottom of the superview: