记录使用masonry时,好用的功能。
文章中记录的功能都是在网上查找到并且实践的功能,文章中是展示关键代码,附上来源网址
父元素根据子元素的高度自适应高度
// 假设父元素boxView_有infoView_和footerView_
boxView_ = [[UIView alloc] init];
[self.view addSubview:boxView_];
infoView_ =[ [UIView alloc] init];
[boxView_ addSubview:infoView_];
footerView_ =[ [UIView alloc] init];
[boxView_ addSubview:footerView_];
// 父元素boxView_不设置高度
[boxView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(20);
make.left.offset(10);
make.right.offset(-10);
}];
[infoView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(300);
make.top.offset(20);
make.left.offset(10);
make.right.offset(-10);
}];
[footerView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(28); // 高度
make.top.equalTo(infoView_.mas_bottom).offset(30); // 与infoView_间隔 30
make.left.offset(10); // 与父元素左边间隔 10
make.right.offset(-10); // 与父元素右边间隔 10
make.bottom.mas_offset(-20); // 与父元素底部间隔 20 关键代码!!
}];
上面代码中,最关键的一句是【make.bottom.mas_offset(-20);】,假设没有这句话,footerView_的布局已经完成了。这句话约束了父元素的底部与footerView的底部关系,实现了父元素的高度自适应
参考文章:https://www.cnblogs.com/lovemargin/p/12208521.html
拓展:UIScroll根据内容自适应滑动高度
scrollView_ = [[UIScrollView alloc] init ];
[self.view addSubview:scrollView_];
[scrollView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.equalTo(self.view);
make.bottom.equalTo(self.view).offset(-80);
}];
containerView_ = [[UIView alloc] init ];
[scrollView_ addSubview:containerView_];
[containerView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(scrollView_);
make.width.equalTo(scrollView_);
}];
// containerView_ 添加子元素
// ...
// 假设containerView_最后一个元素是footerView_
UIView* lastView = footerView_;
[containerView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(lastView.mas_bottom); // 关键代码 !!!
}];
上面代码中,最关键是对containerView_再次设置约束。参考了下面文章中提到的垂直方向的写法。
参考文章:https://www.cnblogs.com/lurenq/p/10567098.html
延伸思考
第一个代码中,在最后一个元素中设置与父元素的约束,实现父元素自适应高度;
这个代码中,设置完所有约束后,再设置父元素与最后一个子元素的约束,实现滑动范围。
尝试用第一个代码实现滑动功能,没有成功,不知道是什么原理。
仿纵向float布局
// 子元素的创建和布局,不需要特殊处理,按照正常的实现;父元素不要设置高度即可
// 假设父元素boxView_有infoView_、likesView_、friendsView_、familyView_
// 其中,likesView_、friendsView_、familyView_根据数据的情况显示或隐藏
// 此时,已经设置完显示/隐藏状态了
UIView* lastView = infoView_;
if(!likesView_.hidden){
[likesView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(lastView.mas_bottom).offset(10);
}];
lastView = likesView_;
}
if(!friendsView_.hidden){
[friendsView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(lastView.mas_bottom).offset(10);
}];
lastView = friendsView_;
}
if(!familyView_.hidden){
[familyView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(lastView.mas_bottom).offset(10);
}];
lastView = familyView_;
}
[boxView_ mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(lastView.mas_bottom);
}];
上面代码,使用的是临时视图的方法。下面文章中,介绍了MasonryFloatLayout的使用,可以学习一下。