简体   繁体   中英

Add constraints based on view's height iOS

I have several subviews which are laid out based on the size of their super view. And I use auto layout here but the size of the super view is always 0, here is the code:

- (instancetype)initWithFrame:(CGRect)frame Count:(NSUInteger)count
{
    self = [super initWithFrame:frame];

    if (self)
    {
        self.count = count;

        const float circleHeight = self.bounds.size.height * (float)4 / (5 * self.count - 1);
        NSLog(@"selfHeight %f",self.bounds.size.height);        

        for (UIImageView * circle in self.circleViewArray)
        {
            [self addSubview:circle];
        }

        for (int i = 0;i < self.count;i++)
        {
            [self.circleViewArray[i] mas_makeConstraints:^(MASConstraintMaker * make){
                make.width.equalTo(self);
                make.height.equalTo(self).multipliedBy((float)4 / (5 * self.count - 1));
                make.centerX.equalTo(self);
                make.bottom.equalTo(self).with.offset(-i * (circleHeight + stickHeight));
            }];
        }
    }

    return self;

}

Note that here I use the third-party Masonry to simplify my code. When I print the "selfHeight" in the console the output is always 0. How should I handle it? 只是看着蓝色的圆圈而忽略其他人

So your offsets are never going to work because they're calculated against zero and never updated. You need to make the constraints relative somehow, or you need to remove and update the constraints each time the frame changes (the layout needs to be updated).

Making the constraints relative is better, which in your case you should look at linking the views together so the spacing between yhen is set and the heights resize to fit the full available height.

Pseudocode:

UIView *previousView = nil;

for (view in views) {

    view.leading = super.leading;
    view.trailing = super.trailing;

    if (previousView) {
        view.top = previousView.bottom;
        view.height = previousView.height; // equal relation, not static height
    } else {
        view.top = super.top;
    }

    previousView = view;
}

previousView.bottom = super.bottom;

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