使用Masonry,布局UIScrollViewView
UIScrollView
比较特殊,frame布局时我们需要设置contentSize
属性
-
初始化ScrollView并添加到父视图 并 进行约束
// ------ 初始化ScrollView UIScrollView *scrollView = UIScrollView.new; self.scrollView = scrollView; scrollView.backgroundColor = [UIColor grayColor]; // ------ 添加到父视图 [self addSubview:scrollView]; // ------ 对ScrollView进行约束 [self.scrollView makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(self); }];
-
初始化ContentView 并进行约束
UIView* contentView = UIView.new; // 添加contentView 到ScrollView上 [self.scrollView addSubview:contentView]; // 约束contentView [contentView makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(self.scrollView); make.width.equalTo(self.scrollView); }];
-
添加子视图到contentView上 并再次对contentView进行约束
UIView *lastView; CGFloat height = 25; for (int i = 0; i < 10; i++) { UIView *view = UIView.new; view.backgroundColor = [self randomColor]; // 注意!!! 这里是添加视图到 contentView上 [contentView addSubview:view]; UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)]; [view addGestureRecognizer:singleTap]; [view mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(lastView ? lastView.bottom : @0); make.left.equalTo(@0); make.width.equalTo(contentView.width); make.height.equalTo(@(height)); }]; height += 25; lastView = view; } // ------>>>>>>: 这里 很关键!!!! [contentView makeConstraints:^(MASConstraintMaker *make) { make.bottom.equalTo(lastView.bottom); }];
讲解
第一次约束是这样的: 先设置下edgs 让contentView能撑起scrollView来。 然后,如果竖直方向高度不固定,就先约束下相对固定的宽度; 如果水平方向宽度不固定,就需要先约束下高度;
// 约束contentView
[contentView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.scrollView);
make.width.equalTo(self.scrollView);
}];
再次更新 加强约束时: 如果竖直方向高度不固定,则需要在此时约束下bottom 或者 top 如果水平方向不固定,则需要在此时约束下 left 或者 right
// ------>>>>>>: 这里 很关键!!!!
[contentView makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(lastView.bottom);
}];