Masonry实现动态宽度依赖布局
Masonry 大家都不陌生,现在简单分享下动态宽度使用心得。先简述下问题,如图:
A、C宽度根据文本内容自适应,B距离A、C之间的间距都是10pt。
直接上代码:
1、A、C不设置宽度,其他约束按照正常设置
[self.bgView addSubview:self.leftBtn]; [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.bgView); make.top.equalTo(self.bgView.mas_top).offset(15); make.height.mas_equalTo(16); }]; [self.bgView addSubview:self.rightBtn]; [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) { make.right.equalTo(self.bgView); make.top.equalTo(self.bgView); make.height.mas_equalTo(18); }]; self.nameLabel = [[UILabel alloc]init]; self.nameLabel.font = IC_TITLE_FONTNAMEWITHSIZE_16; self.nameLabel.textColor = XZWL_COLOR_333333; self.nameLabel.textAlignment = NSTextAlignmentLeft; [self.bgView addSubview:self.nameLabel]; [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) { make.right.equalTo(self.rightBtn.mas_left).offset(-10); make.left.equalTo(self.leftBtn.mas_right).offset(10); make.centerY.equalTo(self.leftBtn); make.height.mas_equalTo(16); }];
2、在赋值地方设置A、C宽度
[self.leftBtn setTitle:leftStr forState:UIControlStateNormal]; CGSize size = [self.leftBtn sizeThatFits:CGSizeZero]; [self.leftBtn mas_updateConstraints:^(MASConstraintMaker *make) { make.width.mas_equalTo(size.width); }]; CardDetailList *detailsModel = model.cardDetailList.firstObject; self.nameLabel.text = ObjErrorCheck(detailsModel.title); if (ObjErrorCheck(detailsModel.statusName).length) { self.rightBtn.hidden = NO; [self.rightBtn setBackgroundColor:[iComeCarrerCircleColorTool getEvaCardStateColor:detailsModel.statusColorType]]; [self.rightBtn setTitle: ObjErrorCheck(detailsModel.statusName) forState:UIControlStateNormal]; CGSize size = [self.rightBtn sizeThatFits:CGSizeZero]; [self.rightBtn mas_updateConstraints:^(MASConstraintMaker *make) { make.width.mas_equalTo(size.width); }]; } else { self.rightBtn.hidden = YES; }