I'm struggling to figure out how to use VFL to accomplish this. I always want the button to be 50 points above the bottom of its superview. I don't want to specify the distance between the top of the bottom and the top of its superview because that will vary across devices.
I was only able to find other similar questions using interface builder, but my project does not use interface builder or swift, but I would like to do this programmatically, in Objective-C.
Thanks in advance.
If you have no idea about how to use VFL, I think you should check the document:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage/VisualFormatLanguage.html
button.translatesAutoresizingMaskIntoConstraints=NO;
NSArray *constraints=[NSLayoutConstraint constraintsWithVisualFormat:#"V:[button]-50-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)];
// add more constraints to satisfy auto layout
[superview addConstraints:constraints];
BTW, I recommend to use Masonry, https://github.com/SnapKit/Masonry, it's more elegant.
Use something like this:
[yourSuperView addConstraint:[NSLayoutConstraint constraintWithItem:yourButton
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:yourSuperView
attribute:NSLayoutAttributeBottomMargin
multiplier:1.0
constant:-50.0]];
You can read more on this here: Working with Auto Layout Programmatically
I'm creating a custom UITableViewCell, but I don't think it makes a difference - my question stands alone.
I'm subclassing one of the existing cell styles, and adding one view. The superclass has a view (a UILabel) that adjusts its vertical positioning within the cell depending on whether or not there is content in another label. If there is content in the second label, the first label is vertically centered between the second label and the top of the cell view.
If the second label doesn't have any content, the first label is vertically centered between the top and the bottom of the cell view.
I like this behavior. I'm trying to add a third label that is horizontally next to the first label. I've used autolayout constraints to pin the new label to be near the first label, like this:
[NSLayoutConstraint constraintsWithVisualFormat:#"[firstLabel]-(5)-[thirdLabel]" options:0 metrics:nil views:views];
This is working fine, but I can't figure out how to do something similar with the vertical position. Ideally, I would "pin" the third label to always be at the same vertical alignment as the first label, no matter what that is, but I don't see how to express that in the visual format language.
As an alternative, figuring out how to replicate the behavior of the first label (adjusting it's vertical alignment based on the presence--or lack of--the second label).
This constraint works to correctly vertically align the new label when the second label is present, but it doesn't do anything if the second label is empty on that particular cell:
[NSLayoutConstraint constraintsWithVisualFormat:#"V:[thirdLabel][secondLabel]" options:0 metrics:nil views:views];
How can I express this layout constraint?
Visual Format Language is best used to create constraints aligning items one after the other.
For more complex layouts like the vertical center alignment you are trying to build, you should use NSLayoutConstraint's constraintWithItem:[...]. method.
Here is what you could do:
[NSLayoutConstraint constraintWithItem:thirdLabel
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:firstLabel
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0];
Hope this helps,
I am in a need of having the series of buttons to be evenly placed in superview Horizontally using Auto Layout.
Here, I want to keep the sizes of the subviews same, only the center of the subviews will be placed in such a way that there is equal number of space between them.
Note: I dont want to set the Size of the superview, I want every thing to be Auto Layout-ed.
Please Help,
I am stuck !!
Thanks!!
You can create as many UIView's as you have buttons, and center the buttons inside the views, the views can be aligned back to back, using this code:
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[view1][view2][view3]|"
options:0
metrics:nil
views:views]];
Make sure you first remove existing constraints from the superview using:
[self.view removeConstraints:self.view.constraints];
and in the viewDidLoad turn off auto resizing conversion:
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
I'm experimenting with how to use UIScrollView. After much trouble, I finally got the hang of it. But now I've seem to hit another snag.
In this simple app, I have a scroll view with and in order for it to work, I have to set the view's bottom space to scrollview constraint to 0 as described here and it works fine. I'm doing it through the IB.
Now I've come across a scenario where I have to do that part programmatically. I've added the below code in the viewDidLoad method.
NSLayoutConstraint *bottomSpaceConstraint = [NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.scrollView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0];
[self.view addConstraint:bottomSpaceConstraint];
But it doesn't seem to work. It outputs the following message in the console window adn i don't know what to make of it.
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"",
""
)
Can someone please tell me how to do this? I've also attached a demo project here so that you can get a better idea on the issue.
UPDATE:
First off thanks for the responses. Using the ways mentioned in the answers I was able to get it working. However ina slightly different scenario its not. Now I'm trying to load a view onto a viewcontroller programatically.
If I may explain further. There are 2 view controllers. First one being a UITableViewController and the second one a UIViewController. Inside that a UIScrollView. Also There are multiple UIViews and some of those views' height exceeds the normal height of the screen.
The UITableViewController displays a list of options. Based on the user's selection, a particular UIView out of the lot will be loaded into the UIViewController with the UIScrollView.
In this scenario, the above method doesn't work. The scrolling isn't happening. Do I have to do something different since I'm loading the view separately?
I've uploaded a demo project here so that you can see it in action. Please see the Email.xib and select Email from the table view list.
Based upon a review of your code, a few comments:
You generally don't need to adjust constraints when a view appears. If you find yourself doing this, it often means that you haven't configured your storyboard correctly (or at least, not efficiently). The only time you really need to set/create constraints is either (a) you're adding views programmatically (which I'm suggesting is more work than it's worth); or (b) you need to do some runtime adjustment of constraints (see third bullet under point 3, below).
I don't mean to belabor it, but your project had a bunch of redundant code. E.g.
You were setting the frame for the scroll view, but that is governed by constraints, so that does nothing (i.e. when the constraints are applied, any manually set frame settings will be replaced). In general, in auto layout, don't try changing frame directly: Edit the constraints. But, no changing of constraints is needed at all anyway, so the point is moot.
You were setting the content size for the scroll view, but in auto layout, that, too, is governed by constraints (of the subviews), so that was unnecessary.
You were setting constraints for the scrollview (which were already zero), but then you weren't adding the view from the NIB into the scrollview, defeating any intent there, too. The original question was how to change the bottom constraint of the scroll view. But the bottom constraint for that is already zero, so I see no reason to set it to zero again.
I'd suggest a more radical simplification of your project:
You're making life much harder on yourself by storing your views in NIBs. It's much easier if you stay within the the storyboard world. We can help you do the NIB stuff if you really need to, but why make life so hard on yourself?
Use cell prototypes to facilitate the design of the cells in your table. You can also define the segues to go from the cells to the next scene. This eliminates any need to write any didSelectRowAtIndexPath or prepareForSegue code. Clearly, if you have something you need to pass to the next scene, by all means use prepareForSegue, but nothing you've presented thus far requires that, so I've commented it out in my examples.
Assuming you were looking for a practical example of programmatically changing constraints, I've set up the scene so that the text view will change its height programmatically, based upon the text in the text view. As always, rather than iterating through the constraints to find the one in question, when altering an existing constraint that IB created for me, I think it's far more efficient to set up an IBOutlet for the constraint, and edit the constant property for the constraint directly, so that's what I've done. So I set up the view controller to be the delegate of the text view, and wrote a textViewDidChange that updated the text view's height constraint:
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
self.textViewHeightConstraint.constant = textView.contentSize.height;
[self.scrollView layoutIfNeeded];
}
Note, my text view has two height constraints, a mandatory minimum height constraint, and a medium priority constraint that I change above based upon the amount of text. The main point is that it illustrates a practical example of changing constraints programmatically. You shouldn't have to muck around with the scrollview's bottom constraint at all, but this is shows a real-world example of when you might want to adjust a constraint.
When you add a scrollview in IB, it will automatically get all the constraints you need. You probably don't want to be adding a constraint programmatically (at least not without removing the existing bottom constraint).
Two approaches might be simpler:
Create an IBOutlet for your existing bottom constraint, say scrollViewBottomConstraint. Then you can just do
self.scrollViewBottomConstraint.constant = 0.0;
Or create your view initially in IB where the bottom constraint is 0.0 and then you don't have to do anything programmatically at all. If you want to layout a long scrollview and it's subviews, select the controller, set it's simulated metrics from "inferred" to "free form". Then you can change the size of the view, set the scrollview's top and bottom constraints to be zero, layout everything you want inside the scroll view, and then when the view is presented at runtime, the view will be resized appropriately, and because you've defined the scrollview's top and bottom constraints to be 0.0, it will be resized properly. It looks a bit odd in IB, but it works like a charm when the app runs.
If you're determined to add a new constraint, you could either programmatically remove the old bottom constraint, or set the old bottom constraints' priority down as low as possible, and that way your new constraint (with higher priority) will take precedence, and the old, low-priority bottom constraint will gracefully not be applied.
But you definitely don't want to just add a new constraint.
It's possible to create outlets to represent layout constraints in your view controller. Just select the constraint you want in interface builder (e.g. via "select and edit" on the measurements pane of the view you are arranging). Then go to the outlets pane and drag a "New Referencing Outlet" to your code file (.h or .m). This will bind the constraint to an NSLayoutConstraint instance that you can access from your controller and adjust dynamically on the fly (generally via the constant property, which is poorly named because it's not a constant at all).
(Note that in XCode 6 you can double-click the constraint to select it for editing.)
Be careful when adjusting the layout in interface builder, however, as you may end up deleting the constraint and have to re-bind it to the outlet.
Looking at the console information, i feel that you are creating ambiguity when you add two same type of constraint.
So instead of creating and adding new constraint, try updating the previous constraint that is already in the constraints array.
for(NSLayoutConstraint *constraint in self.view.constraints)
{
if(constraint.firstAttribute == NSLayoutAttributeBottom && constraint.secondAttribute == NSLayoutAttributeBottom &&
constraint.firstItem == self.view && constraint.secondItem == self.scrollView)
{
constraint.constant = 0.0;
}
}
Hope this helps
Even Rob's answer will work!
You can use https://github.com/SnapKit/Masonry for adding constraints programmatically.
It is power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout.
UIView *superview = self.view;
UIView *view1 = [[UIView alloc] init];
view1.translatesAutoresizingMaskIntoConstraints = NO;
view1.backgroundColor = [UIColor greenColor];
[superview addSubview:view1];
UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
[superview addConstraints:#[
//view1 constraints
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:padding.top],
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:padding.left],
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:-padding.bottom],
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeRight
multiplier:1
constant:-padding.right],]];
in just few lines
Heres the same constraints created using MASConstraintMaker
UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler
make.left.equalTo(superview.mas_left).with.offset(padding.left);
make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom);
make.right.equalTo(superview.mas_right).with.offset(-padding.right);
}];
Or even shorter
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(superview).with.insets(padding);
}];
do your best is sort ;)
I can't find a way to create a 'square' constraint, meaning 'width equals height' in Interface Builder. I guess it's possible to add such constraint programmatically. Is there something I can do in IB? Maybe I just don't see it? It seems trivial, yet I can't find it.
Update Xcode 5.1b5
Ctrl+click and drag from a view and release while the pointer is over the view. Select "Aspect Ratio". It will create a constraint where the first and second item is the view.
Before Xcode 5.1
You can't because the width/height editor lacks the fields to relate to another property or set the ratio:
Therefore, you can't express the following code in Interface Builder:
CGFloat ratio = 1.0;
NSLayoutConstraint *constraint = [NSLayoutConstraint
constraintWithItem:myView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:myView
attribute:NSLayoutAttributeHeight
multiplier:ratio
constant:0];
constraint.priority = 1000;
[myView.superview addConstraint:constraint];
Please add a new constraint, aspect ratio to 1:1 on the UI element as in the image.
To start, control drag diagonally from the button to itself. A contextual menu will appear, where you can add width and height constraints. Shift+Click on each; a checkmark will appear indicating that you have added the constraint. (If you accidentally dismiss the dialog before adding both, that’s OK, just repeat the drag step and set the other one):
When first added, these constraints take on the current width and height of the button, so you’ll need to adjust each constraint to give it a more appropriate value. We’ll have to do this one at a time, although our image is square, so be sure to use the same constant value in both constraints to resize the button proportionally. Double-click on the constraint, and enter a smaller value in its constant field: