Masonry----UIScrollView自动contentSize

前言

Masonry中,在UIScrollView设置约束的时候,是不是被contentSize恶心到了,当我在比较SDAutoLayout和Masonry这两个框架的时候,无意间发现可以自动contentSize, 好啦,进入正题;

正常的来说self.scrollView必须要设置contentSize

self.scrollView.contentSize = CGSizeMake(0, imageView.bottom);
UIScrollView自动布局

这种方式的实现,主要是依赖于创建一个backView内容视图,并添加到UIScrollView上作为子视图。UIScrollView原来的子视图都添加到backView上,并且和这个视图设置约束。

因为对UIScrollView进行addSubview操作的时候,本质上是往其contentView上添加。也就是backView的父视图是contentView,通过backView撑起contentView视图的大小,以此来实现动态改变contentSize。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.scrollView];
    
    UIView *backView = [[UIView alloc] init];
    [self.scrollView addSubview:backView];
    
    UIImage *image = [UIImage imageNamed:@"ml_home_banner_push_image"];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = image;
    [backView addSubview:imageView];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
    }];
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(backView);
        make.width.equalTo(@(kScreenWidth));
        make.height.equalTo(@(kScreenWidth*image.size.height/image.size.width));
        make.bottom.equalTo(backView);
    }];
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
    }
    return _scrollView;
}
知识补充

大于等于和小于等于某个值的约束

[self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.center.equalTo(self.view);
    // 设置宽度小于等于200
    make.width.lessThanOrEqualTo(@200);
    // 设置高度大于等于10
    make.height.greaterThanOrEqualTo(@(10));
}];

你可能感兴趣的:(Masonry----UIScrollView自动contentSize)