一、Masonry实现自适应高度
/// 关键代码
CGFloat MIN_HEIGHT = 28.0f;
CGFloat MAX_HEIGHT = 60.0f;
__block UIView *textContainerView = nil;
[self.textView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:NSClassFromString(@"_UITextContainerView")]) {
textContainerView = obj;
*stop = YES;
}
}];
[self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(TOP_HEIGHT+50);
make.left.offset(50);
make.right.offset(-50);
make.height.mas_equalTo(textContainerView).priorityLow();
make.height.mas_greaterThanOrEqualTo(MIN_HEIGHT);
make.height.mas_lessThanOrEqualTo(MAX_HEIGHT);
}];
二、子类化实现自适应高度
/// 继承UITextView后重写下面方法
/// 关键代码
- (void)setContentSize:(CGSize)contentSize {
[self invalidateIntrinsicContentSize];
super.contentSize = contentSize;
}
- (CGSize)intrinsicContentSize {
CGFloat MIN_HEIGHT = 28.0f;
CGFloat MAX_HEIGHT = 60.0f;
if (self.contentSize.height <= MIN_HEIGHT) {
return CGSizeMake(self.contentSize.width, MIN_HEIGHT);
}
if (self.contentSize.height >= MAX_HEIGHT) {
return CGSizeMake(self.contentSize.width, MAX_HEIGHT);
}
return self.contentSize;
}
/// 使用如下,设置相应约束即可
[self.view addSubview:self.textView];
[self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.offset(TOP_HEIGHT+50);
make.left.offset(50);
make.right.offset(-50);
}];