Skip to content

Instantly share code, notes, and snippets.

@pilky
Created September 3, 2012 14:51
Show Gist options
  • Save pilky/3609846 to your computer and use it in GitHub Desktop.
Save pilky/3609846 to your computer and use it in GitHub Desktop.
NSLayoutConstraint code, done right
//Pass in arrays of views and access with number keys or add attributes for all
NSArray *views = @[ topView, middleView, lastView ];
[containerView setSubviews:views];
[containerView m3_addConstraints:@[
@"$1.top = 0",
@"$2.top = $1.bottom",
@"$3.top = $2.bottom",
@"$3.bottom = 0",
@"$all.(left, right) = (0, 10)", //Assign multiple attributes in one statement
@"$all.height >= 30"
] forViews:views];
//Use dictionaries for named variables. Special keywords "super" and "size" allow quick setting of
//padding to superview (top, leading, bottom, trailing) and view size (width, height)
[contentView addSubview:containerView];
[contentView m3_addConstraints:@[
@"$container.super = (20, 0, 20, 0)", //20 from top & bottom, 0 from left & right
@"$container.size <= (400, 300)"
] forViews:@{ @"container" : containerView }];
//Can access views via KVC.
[myView setContentView:contentView];
[myView m3_addConstraints:@[
@"$self.contentView.super = 0" //If all values of a multiple attribute are equal can assign single constant
] forViews:nil];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment