如何使用 Masonry 将子视图放置在滚动视图中?

How to place a child view inside a scroll view with Masonry?

我想将视图放入 UIScrollView。

Price* p = _entity.prices[0];
    ItemPriceCell *cell = [[ItemPriceCell alloc] initWithFrame:CGRectZero];
    cell.priceLabel.attributedText = [Helper stylePriceLabel:p.priceString withFont:[UIFont fontWithName:@"OpenSans-Semibold" size:34]];
    cell.priceLabel.textColor = [Helper color:self.shop.currentTheme.options.itemPriceTextColor];
    cell.priceNameLabel.text = [NSString stringWithFormat:@"%@",[p definition]];
    cell.priceNameLabel.textColor = [Helper color:self.shop.currentTheme.options.itemDetailTextColor];
    [self.horizontalScrollView addSubview:cell];

现在可以看到价格单元格了。但是如果我添加这段代码:

[cell  mas_updateConstraints:^(MASConstraintMaker *make) {
    make.width.equalTo(@200);
    make.height.equalTo(@50);
    make.top.equalTo(@0);
    make.left.equalTo(@0);
    make.right.equalTo(@0);
    make.bottom.equalTo(@0);
}];

价格视图已隐藏。我哪里错了?

以下代码块中的问题是 topleftbottomright 约束。

[cell mas_updateConstraints:^(MASConstraintMaker *make) {
     make.top.equalTo(@0);
     make.left.equalTo(@0);
     make.right.equalTo(@0);
     make.bottom.equalTo(@0);
}];

在这里,您将顶部约束设置为 0,即单元格的顶部边框为 0。同样,视图的左、右和底部边框为 0。您只添加了 widthheight 你的手机。

根据您在此处给出的约束,iOS auto-layout 系统将单元格的框架获取为 cell.superview.bounds。由此,您的手机不应该被隐藏。它应该占据整个视图。

随时提出修改建议,使它变得更好。如果有任何不清楚的地方或您得到不同的结果,请随时发表评论 :)

更快的选项:

[cell mas_updateConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(@0);
}];