原因:
UIScrollView的leading、 trailing、top、bottom属性由ContentSize决定
ContentSize是根据子视图决定,相互依赖无法正常布局
例:
UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
UIView * view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor redColor];
UIView * view2 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blueColor];
[scrollView addSubview:view1];
[scrollView addSubview:view2];
[self.view addSubview:scrollView];
[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make){
make.edges.mas_equalTo(UIEdgeInsetsZero);
}];
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.bottom.offset(0);
make.mas_equalTo(view2.mas_bottom);
}];
[view2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.bottom.offset(15);
}];
解决:
创建一个大小等于其ContentSize的View覆盖到ScrollView上
其他子视图添加到这个View上
UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
UIView * containView = [[UIView alloc] init];
containView.backgroundColor = [UIColor greenColor];
UIView * view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor redColor];
UIView * view2 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blueColor];
[containView addSubview:view1];
[containView addSubview:view2];
[scrollView addSubview:containView];
[self.view addSubview:scrollView];
[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make){
make.edges.mas_equalTo(UIEdgeInsetsZero);
}];
[containView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(scrollView);
make.width.height.equalTo(scrollView);
}];
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.bottom.offset(0);
make.mas_equalTo(view2.mas_bottom);
}];
[view2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.bottom.offset(15);
}];