scrollView + autoLayout

使用scrollView的时候最烦的就是计算布局的高度,现在下面的这个方法让你告别烦人的技术。

实现的原理:

scrollView上添加一个子视图,然后所有的布局在这个子视图上进行。这其中注意点是子视图的布局还有控件的布局。

看代码吧:
(为了后面方便引用,我把scrllView单独写一个类DWScrollerView)

@interface DWScrollerView : UIScrollView
@property (nonatomic,strong) UIView *container;//内容视图
@end

@implementation DWScrollerView


-(UIView *)container{
    if (!_container) {
        _container = [[UIView alloc] init];
    }
    return _container;
}


- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addSubview:self.container];
        [self.container mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
            make.width.mas_equalTo(self);//如果是垂直方向用width,如果是水平滚动用height
        }];
    }
    return self;
}
@end

怎么引用:

@interface ViewController ()

@property (nonatomic,strong) DWScrollerView *scrollView;

@end

-(void)setupLayout{
    self.scrollView = [[DWScrollerView alloc] init];
    [self.view addSubview:self.scrollView];
}
-(void)setupConstraint{
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupLayout];
    [self setupConstraint];
    UILabel *testLb = [UILabel new];
    testLb.numberOfLines = 0;
    testLb.text = @"对的发放东方红范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿";
    testLb.textColor = [UIColor redColor];
    [self.scrollView.container addSubview:testLb];
    [testLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(90);
        make.width.mas_equalTo(20);
    }];
    UILabel *testLb2 = [UILabel new];
    testLb2.numberOfLines = 0;
    testLb2.text = @"对的发放东方红范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡范德萨发ID搜阿凡达搜啊很高";
    testLb2.textColor = [UIColor blackColor];
    [self.scrollView.container addSubview:testLb2];
    [testLb2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(testLb.mas_bottom).offset(20);
        make.width.mas_equalTo(20);
        make.bottom.mas_equalTo(self.scrollView.container);
    }];
}

可以发现不用计算contentSize就把Label的内容完全显示出来了。

具体代码:scrollViewLayout.zip

你可能感兴趣的:(scrollView + autoLayout)