使用Masonry Lable自动适应文字宽度高度,设置Label的最大宽度值preferredMaxLayoutWidth并且设置numberOfLines=0,才有效果
#pragma mark - 滚动视图自适应
-(void)testScrollView{
self.testScrollerView = [[UIScrollView alloc] init];
self.testScrollerView.pagingEnabled = NO;
[self.view addSubview:self.testScrollerView];
[self.testScrollerView makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
// CGFloat width = [UIScreen mainScreen].bounds.size.width;
UILabel *lastLabel = nil;
for(int i=0; i<20; i++){
UILabel *label = [[UILabel alloc] init];
label.numberOfLines = 0;
label.layer.borderColor = [UIColor greenColor].CGColor;
label.layer.borderWidth = 2;
label.textAlignment = NSTextAlignmentLeft;
label.text = [self randomText];
label.textColor = [self randomColor];
label.preferredMaxLayoutWidth =[UIScreen mainScreen].bounds.size.width - 30;
label.textAlignment = NSTextAlignmentLeft;
label.textColor = [self randomColor];
//不先将视图加入到父视图中使用masonry时会崩溃,崩溃信息A multiplier of 0 or a nil second item together with a location for the firs
[self.testScrollerView addSubview:label];
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(@10);
make.right.mas_equalTo(self.testScrollerView).offset(-15);
if (lastLabel) {
make.top.mas_equalTo(lastLabel.mas_bottom).offset(20);
} else {
make.top.mas_equalTo(self.testScrollerView).offset(20);
}
}];
lastLabel = label;
}
[self.testScrollerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(self.view);
// 让scrollview的contentSize随着内容的增多而变化
make.bottom.mas_equalTo(lastLabel.mas_bottom).offset(20);
}];
}
-(NSString *)randomText {
CGFloat length = arc4random() % 50 + 5;
NSMutableString *str = [[NSMutableString alloc] init];
for (NSUInteger i = 0; i < length; ++i) {
[str appendString:@"测试数据很长,"];
}
return str;
}
- (UIColor *)randomColor {
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}
#pragma mark - 更新view的约束条件
-(void)testUpdateConstrains{
UIButton *updateBtn = [UIButton new];
[updateBtn addTarget:self action:@selector(didTapGrowButton:) forControlEvents:UIControlEventTouchUpInside];
updateBtn.layer.borderWidth = 2;
updateBtn.tag = 100;
updateBtn.layer.borderColor = [UIColor grayColor].CGColor;
[self.view addSubview:updateBtn];
self.buttonSize = CGSizeMake(100, 100);
[updateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.size.equalTo(self.buttonSize).priorityLow();
make.width.and.height.lessThanOrEqualTo(self.view);
}];
updateBtn.translatesAutoresizingMaskIntoConstraints = NO;
}