Add constraints programmatically

In iOS, UI layout has a lot of difficult topic for programmers.

Above iOS6, AutoLayout is coming.
My current team uses programmatically UI style to realize complicated UI.
We can set constraint in xib and storyboard by UI.
But, in case of programmatically, what should we do?

Sample Program

This is just an easy sample!


@interface ConstraintsViewController : UIViewController



#import "ConstraintsViewController.h"

@interface ConstraintsViewController ()
@property (nonatomic) IBOutlet UIButton *button1;
@property (nonatomic) IBOutlet UIButton *button2;


@implementation ConstraintsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    return self;

- (void)viewDidLoad
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button1.translatesAutoresizingMaskIntoConstraints = NO;
    //self.button1.frame = CGRectMake(frame.origin.x, frame.origin.y, 44, frame.size.height);
    self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button1.translatesAutoresizingMaskIntoConstraints = NO;
    [self.button1 setImage:[UIImage imageNamed:@"smile"] forState:UIControlStateNormal];
    [self.button2 setImage:[UIImage imageNamed:@"smile"] forState:UIControlStateNormal];
    [self.view addSubview:self.button1];
    [self.view addSubview:self.button2];
    NSDictionary *viewsDictionary =
    NSDictionaryOfVariableBindings(_button1, _button2);
    NSArray *constraints =
    [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_button1(44)]-10-|"
                                            options:0 metrics:nil views:viewsDictionary];
    [self.view addConstraints:constraints];
    NSArray *constraints2 =
    [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[_button1(44)]"
                                            options:0 metrics:nil views:viewsDictionary];
    [self.view addConstraints:constraints2];


Create UI set with NSDictionaryOfVariableBindings
Create constraints using constraintsWithVisualFormat.
This example I used,
Horizontal, make space 10px at the left side, button1 size(width) is 44px, make space 10px at the right side.
Vertical, make space 10px at the top, button1 size(height) is 44px

constraintsWithVisualFormat is to create constraint format.
Details of the format is in reference pages(next topic).

In this case, I implemented in viewDidLoad.
Actually, this topic is a bit difficult.
I still go on research.


These blog and web site I referenced.
Apple Developer
プログラムによるAuto Layout(Japaneses)
Implementing iOS6 Auto Layout Constraints in Code