I am trying to use the new Auto Layout in Lion because it seems quite nice. But I can not find good information about how to do things. For example:
I have two labels:
This category makes collapsing Auto Layout constrained views really simple:
https://github.com/depth42/AutolayoutExtensions
I just added it to a project and it works great.
Here's an example of how I handled this programmatically rather than using Interface Builder. In summary; I only add the view if it's enabled and then iterate over subviews, adding vertical constraints as I go.
Note that the views in question are initialized prior to this.
/*
Begin Auto Layout
*/
NSMutableArray *constraints = [NSMutableArray array];
NSMutableDictionary *views = [[NSMutableDictionary alloc] init];
/*
Label One
*/
if (enableLabelOne) {
[contentView addSubview:self.labelOne];
self.labelOne.translatesAutoresizingMaskIntoConstraints = NO;
[views setObject:self.labelOne
forKey:@"_labelOne"];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_labelOne(44)]"
options:0
metrics:nil
views:views]];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_labelOne]-|"
options:0
metrics:nil
views:views]];
}
/*
Label Two
*/
if (enableLabelTwo) {
[contentView addSubview:self.labelTwo];
self.labelTwo.translatesAutoresizingMaskIntoConstraints = NO;
[views setObject:self.labelTwo
forKey:@"_labelTwo"];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_labelTwo(44)]"
options:0
metrics:nil
views:views]];
}
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_labelTwo]-|"
options:0
metrics:nil
views:views]];
/*
Dynamically add vertical spacing constraints to subviews
*/
NSArray *subviews = [contentView subviews];
if ([subviews count] > 0) {
UIView *firstView = [subviews objectAtIndex:0];
UIView *secondView = nil;
UIView *lastView = [subviews lastObject];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[firstView]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(firstView)]];
for (int i = 1; i < [subviews count]; i++) {
secondView = [subviews objectAtIndex:i];
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[firstView]-10-[secondView]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(firstView, secondView)]];
firstView = secondView;
}
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastView]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(lastView)]];
}
[self addConstraints:constraints];
I'm only setting the lastView
constraint because this code was adapted from something inside of a UIScrollView.
I originally implemented this based on this Stack Overflow answer and changed things to suit my own needs.