基于 xib 开发自适应高度 view
虽然 xib 和 storyboard 不那么受待见,但我依旧喜欢。
自定义 view

说明:
title Label 约束 -> top:0 bottom:0 left:15
indicator Label 约束 -> top:5 bottom:5 right:34
title Label 和 indicator Label 相对约束 -> 水平间距 >= 5
indicator Label 设置 -> numberOfLines = 0
效果
![]() |
![]() |
![]() |
笔记
使用自适应,也就是不确定约束,多个自适应控件之间不应该出现确定的约束(明确规定 rect 的约束)。
比如: 上面 title Label 和 indicator Label 都使用了自适应(title Label 没有确定宽度或者右边距,indicator Label 没有确定宽度或者左边距),如果这时设置这两个 label 的水平间距为一个确定的值(两个 label 在 xib 上的当前间距除外),约束就会自相矛盾。
核心代码
// 初始化
- (CHDisclosureIndicatorView *) diView {
if (_diView == nil) {
_diView = [[[UINib nibWithNibName:@"CHDisclosureIndicatorView" bundle:nil] instantiateWithOwner:nil options:nil] lastObject];
_diView.layer.cornerRadius = 5;
_diView.delegate = self;
_diView.title = @"默默";
_diView.indicator = nil;
}
return _diView;
}
// 设置约束
[self.diView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.topView.mas_bottom).offset(10);
make.left.mas_equalTo(15);
make.right.mas_equalTo(-15);
make.height.mas_greaterThanOrEqualTo(50); // important
}];