在使用第三方库Masonry的过程中,遇到过各种各样的坑,以下就把笔者使用过程中的问题总结如下:
-
控件必须要添加到父view上之后才可以设置约束
-
一个控件一般需要约束完整,不然会报约束不安全的错误
-
UILabel可以不约束宽高,会根据文本自动填充,
-
设置TableViewCell的高的时候,可以设置cell的高根据子控件来约束,前提是需要将
tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 40;
-
tableView的tableHeadView和tableFootView不可以使用约束,需要使用设置frame
-
当设置scrollView的contentSize的时候,可以根据子控件约束其contentSize,使用一个临时变量的View记录最后一个子View,然后设置约束信息
代码示例:
self.showGreenView = YES;
UIView *redView = [UIView new];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
UIView *orangeView = [UIView new];
orangeView.backgroundColor = [UIColor orangeColor];
[redView addSubview:orangeView];
self.orangeView = orangeView;
UIView *greenView = [UIView new];
greenView.backgroundColor = [UIColor greenColor];
[redView addSubview:greenView];
self.greenView = greenView;
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(0);
make.top.mas_equalTo(70);
}];
[self.orangeView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.mas_equalTo(10);
make.bottom.mas_equalTo(-10);
make.height.mas_equalTo(200);
make.width.mas_equalTo(100);
}];
[self.greenView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.orangeView.right).offset(10);
make.top.bottom.mas_equalTo(self.orangeView);
make.width.mas_equalTo(100);
make.right.mas_equalTo(-10);
}];
redView的大小可以通过子控件orangeView来确定height,greenView来确定width
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.showGreenView = !self.showGreenView;
[self.view setNeedsUpdateConstraints];
[self.view updateConstraintsIfNeeded];
[UIView animateWithDuration:0.25 animations:^{
[self.view layoutIfNeeded];
self.greenView.alpha = self.showGreenView ? 1:0;
}];
}
- (void)updateViewConstraints {
[self.orangeView mas_updateConstraints:^(MASConstraintMaker *make) {
if (self.showGreenView) {
make.width.mas_equalTo(100);
} else {
make.width.mas_equalTo(300);
}
}];
[self.greenView mas_updateConstraints:^(MASConstraintMaker *make) {
if (self.showGreenView) {
make.width.mas_equalTo(100);
} else {
make.width.mas_equalTo(0);
}
}];
[super updateViewConstraints];
}
效果图如下:
网友评论