自定义 IOS TextView,高度自增自减
如何实现UITextView文本框高度随文字行数自动增减呢?
思路1、UITextView的Delegate方法
-textViewDidChange:
在Text变化时计算文字高度,刷新TextView高度
问题:
Text变化与实际有出入,此时的问题变化还没有存储到TextView的Text中,现在进行计算会得到上一个状态下的文字高度,导致TextView高度刷新延迟,换行第二个文字才增加高度,如果采用这个方法,就要进行文字拼接,再计算文字高度。
实现:不够优雅,不实现。
思路2、TextView本质是一个ScrollView
文字高度超出TextView高度会自动增加contentSize属性的height,而且增加的高度刚好就是TextView需要改变的高度,不错。
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| //宽度、高度与坐标
\#define Main_Screen_Height [[UIScreen mainScreen] bounds].size.height \#define Main_Screen_Width [[UIScreen mainScreen] bounds].size.width static float TextViewDefaultHeight = 30.; static float TextViewDefaultY = 5.; static float TextViewContentSizeDefaultHeight = 22.; //测试中使用[UIFont systemFontOfSize:14],每行高度变化为17 self.TextViewInput = [[UITextView alloc]initWithFrame:CGRectMake(45, UUInputTextViewDefaultY, Main_Screen_Width, UUInputTextViewDefaultHeight)]; [self.TextViewInput setContentSize:CGSizeMake(self.TextViewInput.width, UUInputTextViewContentSizeDefaultHeight)]; self.TextViewInput.delegate = self; self.TextViewInput.font = [UIFont systemFontOfSize:14]; self.TextViewInput.textContainerInset = UIEdgeInsetsMake(6,0, 0, 0); //KVO监听TextViewInput的contentSize变化 NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld; [self.TextViewInput addObserver:self forKeyPath:@"contentSize" options:options context:nil]; [self addSubview:self.TextViewInput]; \#pragma mark -- KVO -- - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"contentSize"]){ //最高行数设置,本demo中最高四行,对应paste场景 if (self.TextViewInput.height > UUInputTextViewDefaultHeight+17*2 && self.TextViewInput.contentSize.height > UUInputTextViewContentSizeDefaultHeight+17*2) { return; } //文本为空时处理,对应文字发送、cut场景 if (self.TextViewInput.text.length == 0) { [UIView animateWithDuration:0.3 animations:^{ self.TextViewInput.frame = CGRectMake(45, UUInputTextViewDefaultY, Main_Screen_Width-2*45, UUInputTextViewDefaultHeight); } completion:nil]; return; } CGRect frame = self.TextViewInput.frame; //高度变化值 float changeHeight = self.TextViewInput.contentSize.height - UUInputTextViewContentSizeDefaultHeight; //超过限定高度的场景处理 if (changeHeight > 17*2) { changeHeight = 17*2; } frame.origin.y = UUInputTextViewDefaultY - changeHeight; frame.size.height = UUInputTextViewDefaultHeight + changeHeight; //动画效果 [UIView animateWithDuration:0.3 animations:^{ self.TextViewInput.frame = frame; } completion:nil]; NSLog(@"%lf-- TextViewInput",self.TextViewInput.contentSize.height); } } //注意要注销KVO
-(void)dealloc{ [self.TextViewInput removeObserver:self forKeyPath:@"contentSize"]; }
|