这个例子比较简单,直接看布局的关键代码
- (id)init {
self = [super init];
if (!self) return nil;
UIScrollView *scrollView = UIScrollView.new;
self.scrollView = scrollView;
scrollView.backgroundColor = [UIColor grayColor];
[self addSubview:scrollView];
// scrollView在其父视图上的布局约束
[self.scrollView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self);
}];
[self generateContent];
return self;
}
- (void)generateContent {
UIView* contentView = UIView.new;
[self.scrollView addSubview:contentView];
// scrollView上有一个内容视图,其布局约束如下
[contentView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.scrollView);
make.width.equalTo(self.scrollView);
}];
UIView *lastView;
CGFloat height = 25;
for (int i = 0; i < 10; i++) {
UIView *view = UIView.new;
view.backgroundColor = [self randomColor];
[contentView addSubview:view];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
[view addGestureRecognizer:singleTap];
// 内容视图上的子视图约束
[view mas_makeConstraints:^(MASConstraintMaker *make) {
// lastView为nil,当前视图的top为0,否则当前视图的
// top为lastView的bottom
make.top.equalTo(lastView ? lastView.bottom : @0);
// 当前视图的left为0
make.left.equalTo(@0);
// 当前视图的宽度与内容视图的宽度相等
make.width.equalTo(contentView.width);
// 当前视图的高度为height
make.height.equalTo(@(height));
}];
height += 25;
lastView = view;
}
[contentView makeConstraints:^(MASConstraintMaker *make) {
// 内容视图的bottom为lastView的bottom
make.bottom.equalTo(lastView.bottom);
}];
}
注意:
对于内容视图contentView,设置了如下几个约束:
make.edges.equalTo(self.scrollView);
make.width.equalTo(self.scrollView);
make.bottom.equalTo(lastView.bottom);
这与基本的视图约束是不同的,只因为它是滚动视图的子视图。因为滚动视图的内容是可以超过其自身边界的。