Skip to content

Instantly share code, notes, and snippets.

@vikdenic
Created September 4, 2015 05:05
Show Gist options
  • Select an option

  • Save vikdenic/785d4ae6cdd0bb87956c to your computer and use it in GitHub Desktop.

Select an option

Save vikdenic/785d4ae6cdd0bb87956c to your computer and use it in GitHub Desktop.
Add auto-layout constraints programmatically
-(void)constrainSubview:(UIView *)subview toSuperview:(UIView *)superview {
subview.translatesAutoresizingMaskIntoConstraints = NO;
// initialize
NSLayoutConstraint *width =[NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeWidth
relatedBy:0
toItem:superview
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0];
NSLayoutConstraint *height =[NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeHeight
relatedBy:0
toItem:superview
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0];
NSLayoutConstraint *top = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeTop
multiplier:1.0f
constant:0.f];
NSLayoutConstraint *leading = [NSLayoutConstraint
constraintWithItem:subview
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeLeading
multiplier:1.0f
constant:0.f];
[superview addConstraint:width];
[superview addConstraint:height];
[superview addConstraint:top];
[superview addConstraint:leading];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment