iOS scrollView设置contentsize,在约束情

2021-03-29  本文已影响0人  Amuxiaomu

今天在写scrollview的时候添加子视图后,设置了contentsize,但是scrollview还是无法滚动,就连控件大小也都设置,还是没有效果

    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(2.5);
        make.leading.trailing.mas_offset(0);
        make.bottom.mas_offset(5);
    }];

    [self.view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.mas_offset(0);
        make.width.mas_equalTo(ScreenW);
        make.height.mas_equalTo(250);
    }];

    [self.view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_offset(0);
        make.leading.mas_equalTo(self.view1.mas_trailing);
        make.width.mas_equalTo(ScreenW);
        make.height.mas_equalTo(250);
    }];

最终了解到,如果scrollview使用了约束布局,内部的contentsize会根据约束去计算,那么在布局约束的时候top,bottom,leading,trailing都得设置全
最终解决:

    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(2.5);
        make.leading.trailing.mas_offset(0);
        make.bottom.mas_offset(5);
    }];
    
    [self.view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.bottom.mas_offset(0);
        make.width.mas_equalTo(self.scrollView);
        make.height.mas_equalTo(self.scrollView);
    }];
    
    [self.view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_offset(0);
        make.leading.mas_equalTo(self.view1.mas_trailing);
        make.width.mas_equalTo(self.scrollView);
        make.height.mas_equalTo(self.scrollView);
    }];

之前主要是view2没有设置right(之前是想着子view的大小布局都弄好了,直接设置contentsize就好了,最终怎么设置都没有效果)
结论:只要使用了约束布局(masonry),scrollview的contentsize就会重新根据子view进行计算,如果子view没有吧scrollview完全撑开的话,那么计算就会失败,scrollview就会无法滑动.

参考:AutoLayout深入浅出:UIScrollView中如何设置ContentSize

上一篇下一篇

猜你喜欢

热点阅读