UIScrollView使用Masonry布局最大的难点在于如何让子视图追随ScrollView滑动。
目前使用最广泛的解决方式是为滑动视图添加一个过渡视图,之后将所有的子视图添加到过渡视图上,然后分别设置过渡视图与滑动视图约束(注:竖向滑动时,需将过渡视图的宽度固定;横向滑动时,需将过渡视图的高度固定)、过渡视图与第一个子视图边缘约束、过渡视图与最后一个子视图边缘约束。
本示例以垂直滑动为例:
UIScrollView *scrollView = [[UIScrollView alloc] init];
scrollView.showsVerticalScrollIndicator = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.backgroundColor = [UIColor redColor];
UIView *containerView = [[UIView alloc] init];
containerView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:scrollView];
[scrollView addSubview:containerView];
[scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
[containerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(scrollView);
make.width.equalTo(scrollView.mas_width);
}];
UIView *lastView;
NSInteger viewsNumber = 20;
for (int i = 0; i<viewsNumber; i++) {
UIView *view= [[UIView alloc] init];
view.backgroundColor = [UIColor colorWithRed:(arc4random()%255)/255.0 green:(arc4random()%255)/255.0 blue:(arc4random()%255)/255.0 alpha:1.f];
[containerView addSubview:view];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
if (0 == i) {
//第一个视图
make.top.equalTo(containerView.mas_top);
}else {
make.top.equalTo(lastView.mas_bottom);
}
make.left.equalTo(containerView.mas_left);
make.right.equalTo(containerView.mas_right);
make.height.mas_equalTo(66.f);
if (viewsNumber == i+1) {
//最后一个视图
make.bottom.equalTo(containerView.mas_bottom);
}
}];
lastView = view;
}
效果图:
scrollView.gif
网友评论