本文介绍利用Masonry约束scrollview上的子控件,使得scrollView可以在约束的条件下滚动。核心代码如下:
// 创建scroll view
UIScrollView *scrollView = [[UIScrollView alloc] init];
[self.view addSubview:scrollView];
scrollView.backgroundColor = [UIColor lightGrayColor];
[scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 10, 10, 10));
}];
// 创建scroll view上的子控件
// 第一个子控件
UIView *containerView1 = [[UIView alloc] init];
[scrollView addSubview:containerView1];
containerView1.backgroundColor = [UIColor redColor];
[containerView1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.equalTo(scrollView);
make.height.equalTo(@700);
make.width.equalTo(scrollView);
}];
// 第二个子控件
UIView *containerView2 = [[UIView alloc] init];
[scrollView addSubview:containerView2];
containerView2.backgroundColor = [UIColor blueColor];
[containerView2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(containerView1.mas_bottom);
make.left.equalTo(scrollView);
make.width.equalTo(scrollView);
make.height.equalTo(@100);
}];
// 更新scroll view的约束,scroll view的底部等于其最后一个子控件的底部
[scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(containerView2.mas_bottom);
}];
注意点有:
1.scrollView上的子控件约束要完整。
2.当scrollView上的子控件更新时,要更新scrollView的约束。要使得scrollView的底部等于其最后子控件的底部。
3.注意使用约束方法。