在UI开发过程中,经常出现view显示与隐藏的逻辑,也就是说当上面的view隐藏时,需要下面的view顶上来,如:
正常情况 | 2隐藏 | 2,4隐藏 |
---|---|---|
view1 | view1 | view1 |
view2 | view3 | view3 |
view3 | view4 | view5 |
view4 | view5 | |
view5 |
我们在用Masonry布局的时候,实现上面的需求,同时需要view自适应高度,往往需要根据data属性设置view的高度或者隐藏,导致里面判断极其繁琐,现在突然想到一个牛逼闪闪的点子,特意记录一下:(如果你有更好的方式,留言,但是不要嘲笑😝)
1:初始化view:这里面把所有的view都初始化,管他后面会不会有用
2:获取数据后刷新view:这里设置对应view的hidden属性,不过不显示就设置为NO
3:layoutSubviews中布局:
3-1: 定义一个零时的view = nil
3-2: 判断view1是否要显示,如果显示,对view 布局,同时将view = view1
3-3: 如果不显示,就用2方法判断view2 依此类推 ,同时view2的top布局相对于view的底部
3-4:在最后一个view布局的时候不要添加对底部了依赖
3-5:最后添加零时view地底部相对于底部的依赖即可
-(instancetype)initWithFrame:(CGRect)frame{
if (self == [super initWithFrame:frame]) {
[self confitUI];
}
return self;
}
-(void)confitUI{
self.view1 = [UIView new];
[self addSubview:_view1];
self.view2 = [UIView new];
[self addSubview:_view1];
self.view3 = [UIView new];
[self addSubview:_view1];
self.view4 = [UIView new];
[self addSubview:_view1];
self.view5 = [UIView new];
[self addSubview:_view1];
}
-(void)reload:(TestData*)data{
if(data.one){
view1.hidden = YES;
}
if(data.tow){
view2.hidden = YES;
}
if(data.thir){
view3.hidden = YES;
}
if(data.foun){
view4.hidden = YES;
}
if(data.five){
view5.hidden = YES;
}
}
-(void)layoutSubviews{
[super layoutSubviews];
UIView *temView = nil;
if(! _view1.hidden){
[_view1 mas_makeConstraints:^(MASConstraintMaker *make) {
if(temView){
make.top.mas_equalTo(temView.mas_bottom);
}else{
make.top.mas_equalTo(self);
}
make.left.mas_equalTo(self);
make.width.mas_equalTo(300);
}];
temView = view1;
}
if(! _view2.hidden){
[_view1 mas_makeConstraints:^(MASConstraintMaker *make) {
if(temView){
make.top.mas_equalTo(temView.mas_bottom);
}else{
make.top.mas_equalTo(self);
}
make.left.mas_equalTo(self);
make.width.mas_equalTo(300);
}];
temView = view2;
}
if(! _view3.hidden){
[_view3 mas_makeConstraints:^(MASConstraintMaker *make) {
if(temView){
make.top.mas_equalTo(temView.mas_bottom);
}else{
make.top.mas_equalTo(self);
}
make.left.mas_equalTo(self);
make.width.mas_equalTo(300);
}];
temView = view3;
}
...
[temview mas_updateConstraints:^(MASConstraintMaker *make) {
make.bottom.mas_equalTo(self.contView).mas_offset(-Panding_DEF);
}];
}
网友评论