简体   繁体   中英

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?

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)
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM