Skip to content

Instantly share code, notes, and snippets.

@trm36
Created February 24, 2015 19:13
Show Gist options
  • Save trm36/90b973ef6faeb838f4f6 to your computer and use it in GitHub Desktop.
Save trm36/90b973ef6faeb838f4f6 to your computer and use it in GitHub Desktop.
Auto Layout Programmatically
UITextField *textField1 = [UITextField new];
textField1.placeholder = @"UITextField 1";
textField1.borderStyle = UITextBorderStyleRoundedRect;
textField1.backgroundColor = [UIColor redColor];
[textField1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:textField1];
UITextField *textField2 = [UITextField new];
textField2.placeholder = @"UITextField 2";
textField2.borderStyle = UITextBorderStyleRoundedRect;
textField2.backgroundColor = [UIColor blueColor];
[textField2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:textField2];
NSLayoutConstraint *leadingConstraint =
[NSLayoutConstraint constraintWithItem:textField1
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeading
multiplier:1.0
constant:10];
[self.view addConstraint:leadingConstraint];
NSLayoutConstraint *trailingConstraint =
[NSLayoutConstraint constraintWithItem:textField2
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:-10];
[self.view addConstraint:trailingConstraint];
NSLayoutConstraint *top1Constraint =
[NSLayoutConstraint constraintWithItem:textField1
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:35];
[self.view addConstraint:top1Constraint];
NSLayoutConstraint *top2Constraint =
[NSLayoutConstraint constraintWithItem:textField2
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:35];
[self.view addConstraint:top2Constraint];
NSLayoutConstraint *equalWidthConstraint =
[NSLayoutConstraint constraintWithItem:textField1
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:textField2
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0];
[self.view addConstraint:equalWidthConstraint];
NSLayoutConstraint *spacingConstraint =
[NSLayoutConstraint constraintWithItem:textField2
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:textField1
attribute:NSLayoutAttributeTrailing
multiplier:1.0
constant:-10];
[self.view addConstraint:spacingConstraint];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment