6

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?

Tiago Veloso
  • 8,513
  • 17
  • 64
  • 85
  • Your code works for me, can you explain what does not work on your side? If the view has to be inside its superview, calling `make.centerX` will not be enough, to also position it vertically inside the view call `make.center.equalTo(b)`. – Daehn Sep 03 '15 at 15:42
  • Ah, sorry, I only want to center horizontally. To me when I use that constraint (in my example) the subview does not show. – Tiago Veloso Sep 03 '15 at 15:55

1 Answers1

7

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)
}];
joern
  • 27,354
  • 7
  • 90
  • 105