UIScrollView+Masonry 解决view展示异常

原因:

UIScrollView的leading、 trailing、top、bottom属性由ContentSize决定

ContentSize是根据子视图决定,相互依赖无法正常布局

例:

    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];

    UIView * view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor redColor];
    
    UIView * view2 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor blueColor];
    
    [scrollView addSubview:view1];
    [scrollView addSubview:view2];
    [self.view addSubview:scrollView];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make){
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
        make.mas_equalTo(view2.mas_bottom);
    }];
    
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(15);
    }];
复制代码

解决:

创建一个大小等于其ContentSize的View覆盖到ScrollView上

其他子视图添加到这个View上

    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    
    UIView * containView = [[UIView alloc] init];
    containView.backgroundColor = [UIColor greenColor];
    
    UIView * view1 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor redColor];
    
    UIView * view2 = [[UIView alloc] init];
    view1.backgroundColor = [UIColor blueColor];
    
    [containView addSubview:view1];
    [containView addSubview:view2];
    [scrollView addSubview:containView];
    [self.view addSubview:scrollView];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make){
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView);
        make.width.height.equalTo(scrollView);
    }];
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(0);
        make.mas_equalTo(view2.mas_bottom);
    }];
    
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.offset(15);
    }];
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值