Skip to content

Instantly share code, notes, and snippets.

@bdolman
Created April 13, 2013 18:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdolman/5379465 to your computer and use it in GitHub Desktop.
Save bdolman/5379465 to your computer and use it in GitHub Desktop.
Example of the use of even spacing constraints in a view controller (using the category from this answer: http://stackoverflow.com/questions/13075415/evenly-space-multiple-views-within-a-container-view/14568394#14568394)
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *label1 = [UILabel new];
UILabel *label2 = [UILabel new];
UILabel *label3 = [UILabel new];
UILabel *label4 = [UILabel new];
[label1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[label2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[label3 setTranslatesAutoresizingMaskIntoConstraints:NO];
[label4 setTranslatesAutoresizingMaskIntoConstraints:NO];
label1.text = @"Label 1";
label2.text = @"Label 2";
label3.text = @"Label 3";
label4.text = @"Label 4";
[self.view addSubview:label1];
[self.view addSubview:label2];
[self.view addSubview:label3];
[self.view addSubview:label4];
// Space the labels evenly along the vertical axis
NSArray *constraints = [NSLayoutConstraint constraintsForEvenDistributionOfItems:@[label1, label2, label3, label4]
relativeToCenterOfItem:self.view
vertically:YES];
[self.view addConstraints:constraints];
// Center each label horizontally
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label1
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label2
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label3
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label4
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f]];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment