Search code examples
iosmasonry-ios-osx

Centering a view within it's superview with Masonry


I am trying to use Masonry for iOS. I have a label and a view.

I want to add the label to the view and center it horizontally in the view.

However the constraint I create with masonry does not work correctly.

UILabel *a = [UILabel new];
a.text = @"Hi";
a.textColor = [UIColor blackColor];
[a sizeToFit];

UIView *b = [UIView new];
b.frame = CGRectMake(0, 0, CGRectGetWidth(a.frame) + 18.0f, 19.0f);
[b addSubview:a];

[a mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(b.mas_centerX);
}];

How to center a view within it's "superview" correctly with Masonry?


Solution

  • It works if you add a top constraint:

    [a mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0)
        make.centerX.equalTo(b);
    }];
    

    However you could auto-layout all the way and get rid of setting the frame and sizeToFit stuff:

    UILabel *a = [UILabel new];
    a.text = @"Hi";
    a.textColor = [UIColor blackColor];
    
    UIView *b = [UIView new];
    [b addSubview:a];
    
    [a mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.centerX.equalTo(b);
    }];
    
    [b mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(a).with.offset(18)
        make.height.equalTo(a)
    }];