UIScrollView
是个非常特殊的view
,UIScrollView
与其subview
之间相对位置的约束,并不会直接用于frame
的计算,而是会转化为对ContentSize
的计算。换句话说,当UIScrollView
知道了上下左右的约束分别指向subview
什么位置之后,只要subview
的位置固定下来了,ContentSize
的大小就确定下来了。
@interface Example1Controller ()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *containView;
@end
@implementation Example1Controller
- (void)viewDidLoad {
[super viewDidLoad];
[self addPageSubviews];
[self layoutPageSubviews];
}
- (void)addPageSubviews {
[self.view addSubview:self.scrollView];
[self.scrollView addSubview:self.containView];
[self.containView addSubview:self.topView];
[self.containView addSubview:self.bottomView];
}
- (void)layoutPageSubviews {
[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.width.mas_equalTo(300);
make.height.mas_equalTo(300);
}];
[self.containView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.scrollView);
make.width.equalTo(self.scrollView);
// make.height.equalTo(self.scrollView).multipliedBy(1.5);
}];
[self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.containView);
make.leading.equalTo(self.containView);
make.trailing.equalTo(self.containView);
make.height.mas_equalTo(200);
}];
[self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.topView.mas_bottom);
make.leading.equalTo(self.containView);
make.trailing.equalTo(self.containView);
make.height.mas_equalTo(200);
make.bottom.equalTo(self.containView);
}];
}
#pragma mark - getter & setter
-(UIView *)containView {
if (!_containView) {
_containView = [[UIView alloc] init];
_containView.backgroundColor = [UIColor blueColor];
}
return _containView;
}
-(UIScrollView *)scrollView {
if (!_scrollView) {
_scrollView = [[UIScrollView alloc] init];
_scrollView.backgroundColor = [UIColor redColor];
}
return _scrollView;
}
- (UIView *)topView {
if (!_topView) {
_topView = [[UIView alloc] init];
_topView.backgroundColor = [UIColor grayColor];
}
return _topView;
}
-(UIView *)bottomView {
if (!_bottomView) {
_bottomView = [[UIView alloc] init];
_bottomView.backgroundColor = [UIColor yellowColor];
}
return _bottomView;
}
@end