今天小编在写根据文本输入动态修改TextView的时候 高度计算不准确问题
- 可以使用sizeTofit计算,但是也不精准,还需要计算内间距 看到其他侠客都不沾此邪术 小编也修炼了下方内功
- 使用contentSize监听
(衷心提示:注意仔细阅读 - 读到最后 你就赚了)
//---------------添加监听-----------------
[textView addObserver: self
forKeyPath: @"contentSize"
options: NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
context: nil];
//---------------------------------------
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"contentSize"]) {
CGFloat oldHeight = [change[@"old"]CGSizeValue].height;
CGFloat newHeight = [change[@"new"]CGSizeValue].height;
if (oldHeight <= 0 || newHeight <= 0) return;
if (oldHeight != newHeight) {
UITextView *textView = object;
CGSize size = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)];
if (size.height > newHeight) {
return;
}
// msgTextDefaultheight: 文本框最小的高度
CGFloat msgTextDefaultheight = 40;
CGFloat inputHeight = newHeight > msgTextDefaultheight ? newHeight : msgTextDefaultheight;
// 更新相关frame
[self msgTextViewHeightFit:inputHeight];
}
}
}
这里需要有一点注意的问题 也是小编在根据textView.frame变化的时候有些动画 才发现的问题
当在文本输入的时候 ,有可能会出现 走两次 监听方法
*** 第一次 newHeight 计算的是少了一行内容后的高度
*** 第二次 newHeight 计算的是正确的
如果有其他View的UI变化与当前textViewframe联动 就会出现闪变的bug,
小编为了去掉第一次错误计算,添加了下面的判断:
//
if (size.height > newHeight) {
return;
}
通过sizeToFit 计算的高度 与当前new 的值 进行比较
如果 size.height > newHeight 那么当前一定是错误的