简体   繁体   English

根据视图的高度添加约束iOS

[英]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: 我在这里使用自动布局,但是超级视图的大小始终为0,这是代码:

- (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? 当我在控制台中打印“ selfHeight”时,输出始终为0。如何处理? 只是看着蓝色的圆圈而忽略其他人

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. 使约束成为相对更好,在您的情况下,您应该查看将视图链接在一起,以便设置yhen之间的间距,并调整高度以适合整个可用高度。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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