问题:
直接在scrollview上addSubview,往往出偏差
解决办法:
是加一层容器containerView做间隔,containerView add到scrollview上,自定义的子view add到containerView上
然后重点是:在containerView的mas设置block中
需要竖向滑动时设置 width
make.width.equalTo(scrollView);
需要横向滑动时设置 height
make.height.equalTo(scrollView);
示例
- (void)setupUI {
//scrollview加到controller的self.view上
[self.view addSubview:self.backgroundScrollView];
//容器containerView加到scrollview上
[self.backgroundScrollView addSubview:self.containerView];
//子view加到容器containerView上
[self.containerView addSubview:self.subViewA];
[self.containerView addSubview:self.subViewB];
}
- (void)addConstraints {
[self.backgroundScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.equalTo(self.view);
make.bottom.equalTo(self.view).offset(-TAB_BAR_HEIGHT);
}];
[self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.bottom.right.equalTo(self.backgroundScrollView);
//主要是这里,如下是竖向滑动,就设置width同scrollview
make.width.equalTo(self.backgroundScrollView);
}];
[self.subViewA mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.equalTo(self.containerView);
}];
[self.subViewB mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.subViewA.mas_bottom).offset(16);
make.left.right.bottom.equalTo(self.containerView);
}];
}
该博客主要介绍了在使用Swift开发iOS应用时,如何处理ScrollView添加子视图时出现的位置偏差问题。通过在ScrollView上添加一层ContainerView作为间隔,并将自定义视图添加到ContainerView中,然后通过AutoLayout设置约束,确保视图在滑动时正确显示。关键在于设置ContainerView的宽度或高度等于ScrollView,以实现竖向或横向滑动。示例代码展示了具体的实现步骤。
1万+

被折叠的 条评论
为什么被折叠?



