UIScrollView autoLayout

121 阅读1分钟

在 scrollView 中对其 subviews 使用自动布局时,需要设置 contentSize ,否则可能无法达到预期的约束。因为使用自动布局,无法指定 contentSize 的大小,可以借助添加一个 containerView 的手段来达到相同的目的。

    UIView *container = [UIView new];
    [scrollView addSubview:container];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView);
        // 此处指定的是宽度, scrollView 垂直滚动;若要水平滚动只需指定高度即可.
        make.width.equalTo(scrollView);
    }];
    
    // 在 scrollView 中布局其他 view
    UIView *view = [UIView new];
    [scrollView addSubview:view];
    [container mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(scrollView);
        make.height.mas_equalTo(40);
    }];
    ...