Masonry 在UISCrollView 上的使用 (自动填充适配contentSize)

前言

相信很多人都在使用masory进行手动纯代码布局.而Masonry在代码的高可阅读性,和其优美的语法,也成为了我的首选.在大多数情况下,masonry 都可以很简单的就完成布局,但是在对UISCrollView进行自动布局时,会存在UISCrollView的子视图在超出UISCrollView边界后, UISCrollView 还无法滚动的问题,针对这个问题,本文举了一个简单的例子,Demo已上传GitHub

Masonry 在UISCrollView 上的使用

  • 需要的控件
@property (nonatomic, readwrite, strong) UIScrollView *scrollView;//滚动视图
@property (nonatomic, readwrite, strong) UIView *mas_heighContentView;//用来获取contentSize 高度的视图
@property (nonatomic, readwrite, strong) UIView *contentView;//真正的scrollView 内部承载视图
@property (nonatomic, readwrite, strong) UIView *topView;//contentView的子视图,
@property (nonatomic, readwrite, strong) UIView *bottomView;//contentView的子视图,在这里会被设置为超过屏幕
  • 层级
[self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.mas_heighContentView];
    [self.scrollView addSubview:self.contentView];
        [self.contentView addSubview:self.topView];
        [self.contentView addSubview:self.bottomView];
  • 进行布局
[self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
    make.edges.equalTo(self.view);
}];
    [self.mas_heighContentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.scrollView);
        //这里的底部关联scrollView 最底部的视图,使self.contentView可以拿到 mas_height
        make.bottom.equalTo(self.bottomView);
    }];
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        //必须设置宽度 mas_right 对scrollView 没用
        make.width.equalTo(self.scrollView);
        
        //必须设置高度,用来撑开contentSize
        make.height.equalTo(self.mas_heighContentView);
    }];
        [self.topView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(50);
            make.centerX.equalTo(self.contentView);
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(300);
        }];
            
        [self.bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.topView.mas_bottom).offset(200);
            make.centerX.equalTo(self.contentView);
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(500);
        }];
  • 最终效果


    最终效果.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。