Masonry多行多列布局

2021-03-16  本文已影响0人  王煜仁
    for (UIView *view in self.containerView.subviews) {
        [view removeFromSuperview];
    }
    UIView *firstView;/// 记录每行第一个view
    UIView *lastView;/// 记录当前view
    CGFloat space = 25.f;/// 这个间距设置的是子控件距离父视图上下左右以及子视图之间的间距,请根据需要设置相关参数
    int col = 3;/// 定义列数
    for (int i = 0; i < 控件数量数组.count; i++) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = UIColor.redColor;
        [self.containerView addSubview:view];
        if (i % col == 0) {
            firstView = view;
        }
        if (lastView) {
            if (i % col == 0) {
                [view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(lastView.mas_bottom).offset(space);
                    make.left.equalTo(self.containerView).offset(space);
                    make.width.equalTo(lastView);
                }];
            } else {
                [view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(lastView.mas_right).offset(space);
                    make.top.width.equalTo(lastView);
                    if (i % col == col - 1) {///这边是设置每行最后一个view的约束
                        make.right.equalTo(self.containerView).offset(-space);
                    }
                }];
            }
        } else {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.containerView).offset(12);
                make.left.equalTo(self.containerView).offset(space);
            }];
        }
        lastView = view;
    }
  /// 添加最后一个view的bottom约束,这样就可以撑开整个containerView了,可以做到根据控件数量自适应高度
    [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.containerView).offset(-25);
    }];

这是我写在自定义视图中的布局,请根据需要做相应调整,核心代码已贴出

上一篇 下一篇

猜你喜欢

热点阅读