Skip to content

Instantly share code, notes, and snippets.

@akashgupta88
Created November 1, 2015 19:10
Show Gist options
  • Save akashgupta88/2ff3324e972c396f1039 to your computer and use it in GitHub Desktop.
Save akashgupta88/2ff3324e972c396f1039 to your computer and use it in GitHub Desktop.
For adding views instantiated from nibs quickly along with opinionated Autolayout Constraints.
#import <UIKit/UIKit.h>
@interface UIView (AddSubviewWithConstraints)
-(void)addSubview:(UIView *)view withConstraintInsets:(UIEdgeInsets)insets;
@end
#import "UIView+AddSubviewWithConstraints.h"
@implementation UIView (AddSubviewWithConstraints)
-(void)addSubview:(UIView *)view withConstraintInsets:(UIEdgeInsets)insets
{
view.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:view];
[self addConstraints:@[
[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self attribute:NSLayoutAttributeTop
multiplier:1.0
constant:insets.top],
[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeLeading multiplier:1.0
constant:insets.left],
[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:-insets.right],
[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:-insets.bottom]
]];
[self layoutIfNeeded];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment