Skip to content

Instantly share code, notes, and snippets.

@kongtomorrow
Created October 8, 2014 19:53
Show Gist options
  • Save kongtomorrow/6d5b947bd0fdd2480cf8 to your computer and use it in GitHub Desktop.
Save kongtomorrow/6d5b947bd0fdd2480cf8 to your computer and use it in GitHub Desktop.
@interface UIView (LayoutConvenience)
- (NSLayoutConstraint *)constraintAligningAttribute:(NSLayoutAttribute)attr withView:(UIView *)otherView;
@end
@implementation UIView (LayoutConvenience)
- (NSLayoutConstraint *)constraintAligningAttribute:(NSLayoutAttribute)attr withView:(UIView *)otherView {
return [NSLayoutConstraint constraintWithItem:self attribute:attr relatedBy:NSLayoutRelationEqual toItem:otherView attribute:attr multiplier:1.0 constant:0.0];
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label1 = [[UILabel alloc] init];
label1.text = @"Label 1";
label1.textAlignment = NSTextAlignmentCenter;
UILabel *label2 = [[UILabel alloc] init];
label2.text = @"Label 2";
label2.textAlignment = NSTextAlignmentCenter;
label2.font = [UIFont systemFontOfSize:40];
UIView *groupingView = [[UIView alloc] init];
[[self view] addSubview:groupingView];
[groupingView addSubview:label1];
[groupingView addSubview:label2];
id views = NSDictionaryOfVariableBindings(label1,label2,groupingView);
for (UIView *view in [views allValues]) {
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
}
[[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label1]|" options:0 metrics:nil views:views]];
[[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label2]|" options:0 metrics:nil views:views]];
[[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label1][label2]|" options:0 metrics:nil views:views]];
[[self view] addConstraint:[[self view] constraintAligningAttribute:NSLayoutAttributeCenterX withView:groupingView]];
[[self view] addConstraint:[[self view] constraintAligningAttribute:NSLayoutAttributeCenterY withView:groupingView]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment