05B11B7DDD2F608AD10DB48D8D84A419.png
最近需要做一個近似于MBProgressHUD功能的一個控件,于是就仔細(xì)看了看MBProgressHUD的源碼受扳⌒辏總的來說,它的重點在于HUD初始化勘高、show峡蟋、hide方法,以及視圖的處理方式华望,但是難點個人認(rèn)為在于autolayout蕊蝗。它是用系統(tǒng)的約束布局,看起來比較苦澀難懂赖舟,除非對系統(tǒng)約束比較熟悉蓬戚。
現(xiàn)在大多數(shù)項目的布局都是用的第三方布局工具M(jìn)asonry,我個人也是相對用的比較順手宾抓,重要的是我對系統(tǒng)布局沒什么研究子漩,所以在封裝控件的時候就用的Masonry。
如何使用Masonry根據(jù)子視圖size改變父視圖size是這篇文章要解決的問題
如上圖石洗,我想在紅色的bgView上放兩個UILabel(label幢泼、detailLabel),bgView最大width是它的左右邊緣距離父視圖左右邊緣都是20px劲腿;兩個label的最大width是它的左右邊緣距離父視圖左右邊緣都是10px旭绒;bgView的最小size是400px*400px。
直接上代碼吧,仔細(xì)想想就可以理解為什么要這樣做:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addSubview:self.bgView];
[self.bgView addSubview:self.label];
[self.bgView addSubview:self.detailLabel];
[_label mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.bgView);
make.height.mas_equalTo(40);
make.width.lessThanOrEqualTo(self.bgView).mas_offset(-10);
}];
[_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.bgView);
make.top.mas_equalTo(_label.mas_bottom).mas_offset(10);
make.height.mas_equalTo(40);
make.width.lessThanOrEqualTo(self.bgView).mas_offset(-10);
}];
[_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.height.mas_equalTo(200);
make.width.mas_equalTo(200).priorityLow();
make.width.lessThanOrEqualTo(self.view).mas_offset(-20);
}];
}
- (UIView *)bgView {
if (!_bgView) {
_bgView = [[UIView alloc] init];
_bgView.backgroundColor = [UIColor redColor];
}
return _bgView;
}
- (UILabel *)label {
if (!_label) {
_label = [[UILabel alloc] init];
_label.textAlignment = NSTextAlignmentCenter;
_label.text = @"[UIColor brownColor]";
_label.backgroundColor = [UIColor brownColor];
}
return _label;
}
- (UILabel *)detailLabel {
if (!_detailLabel) {
_detailLabel = [[UILabel alloc] init];
_detailLabel.textAlignment = NSTextAlignmentCenter;
_detailLabel.text = @"這是detailLabelMBProgressHUDMBProgressHUD";
_detailLabel.backgroundColor = [UIColor brownColor];
}
return _detailLabel;
}
這只是一個例子挥吵,舉一反三適用于很多場景重父。