Skip to content

Instantly share code, notes, and snippets.

@haxpor
Created September 29, 2015 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxpor/8f37dc570902d514d09e to your computer and use it in GitHub Desktop.
Save haxpor/8f37dc570902d514d09e to your computer and use it in GitHub Desktop.
Create iOS constraints in code
...
UIView* contentView = [[UIView alloc] init];
contentView.translatesAutoresizingMaskIntoConstraints = NO;
contentView.backgroundColor = [UIColor grayColor];
contentView.layer.cornerRadius = 12.0;
UILabel* statusLabel = [[UILabel alloc] init];
statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.textColor = [UIColor whiteColor];
statusLabel.font = [UIFont boldSystemFontOfSize:12.0];
statusLabel.numberOfLines = 0; // cover all lines
statusLabel.text = text;
[contentView addSubview:statusLabel];
NSDictionary* views = NSDictionaryOfVariableBindings(contentView, statusLabel);
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(16)-[statusLabel]-(10)-|"
options:NSLayoutFormatAlignAllCenterX
metrics:nil
views:views]];
[contentView addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(36)-[statusLabel]-(36)-|"
options:0
metrics:nil
views:views]];
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment