Skip to content

Instantly share code, notes, and snippets.

@vienvu89
Last active January 11, 2016 01:25
Show Gist options
  • Save vienvu89/07c7fcaef5dcdc627ab0 to your computer and use it in GitHub Desktop.
Save vienvu89/07c7fcaef5dcdc627ab0 to your computer and use it in GitHub Desktop.
Sometimes when add child view controller programmatically and just add subview fill all container. You have to add constraint again and again. This snip set code will help you add by one line of code.
//
// CommonAutolayoutUtils.h
// Vien Vu
//
// Created by Vien Vu on 1/8/16.
// Copyright © 2016 Vien Vu. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface CommonAutolayoutUtils : NSObject
+ (void)addConstraintsChildToContainer:(UIView *) parent childView:(UIView *)child;
+ (void)addConstraintsChildToContainer:(UIView *) parent childView:(UIView *)child insets:(UIEdgeInsets)inset;
@end
.m File
//
// CommonAutolayoutUtils.m
// Vien Vu
//
// Created by Vien Vu on 1/8/16.
// Copyright © 2016 Vien Vu. All rights reserved.
//
#import "CommonAutolayoutUtils.h"
@implementation CommonAutolayoutUtils
+ (void)addConstraintsChildToContainer:(UIView *)parent childView:(UIView *)child {
NSDictionary *views =@{@"childView": child,@"container": parent};
//Horizontal constraints
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[childView]|" options:0 metrics:nil views:views];
[parent addConstraints:horizontalConstraints];
//Vertical constraints
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[childView]|" options:0 metrics:nil views:views];
[parent addConstraints:verticalConstraints];
}
+ (void)addConstraintsChildToContainer:(UIView *)parent childView:(UIView *)child insets:(UIEdgeInsets)inset {
NSDictionary *views =@{@"childView": child,@"container": parent};
//Horizontal constraints
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|-%f-[childView]-%f-|", inset.left, inset.right] options:0 metrics:nil views:views];
[parent addConstraints:horizontalConstraints];
//Vertical constraints
NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|-%f-[childView]-%f-|", inset.top, inset.bottom] options:0 metrics:nil views:views];
[parent addConstraints:verticalConstraints];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment