今天朋友有个奇怪的需求
要求UITextView根据内容调整自身的大小,当超过某个高度后,不再变化
步骤
-
定义UITextView的子类
@interface AutoHeightTextView : UITextView
-
添加最大高度的属性
@property (nonatomic, assign) CGFloat maxHeight;
注册监听者:监听内容变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFrame) name:UITextViewTextDidChangeNotification object:nil];
设置自身大小
- (void)changeFrame {
CGFloat maxH = self.maxHeight;
CGRect frame = self.frame;
CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
CGSize size = [self sizeThatFits:constraintSize];
if (size.height <= frame.size.height) {
size.height = frame.size.height;
} else {
if (size.height >= maxH) {
size.height = maxH ;
self.scrollEnabled = YES;
} else {
self.scrollEnabled = NO;
}
}
self.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
[self layoutSubviews];
}
再次申明:这是一个奇怪的需求,所以就写了奇怪的代码,其中还有很多不足。例如,最大高度比原来的高度还小,或者不设置都会有小问题。