UIScrollView+Masonry 解決view展現異常

緣由:

UIScrollView的leading、 trailing、top、bottom屬性由ContentSize決定bash

ContentSize是根據子視圖決定,相互依賴沒法正常佈局佈局

例:spa

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上code

其餘子視圖添加到這個View上it

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);
    }];
複製代碼
相關文章
相關標籤/搜索