masonry 在UIScrollview上布局

该博客主要介绍了在使用Swift开发iOS应用时,如何处理ScrollView添加子视图时出现的位置偏差问题。通过在ScrollView上添加一层ContainerView作为间隔,并将自定义视图添加到ContainerView中,然后通过AutoLayout设置约束,确保视图在滑动时正确显示。关键在于设置ContainerView的宽度或高度等于ScrollView,以实现竖向或横向滑动。示例代码展示了具体的实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

直接在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);
    }];
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值