YYText
YYText copied to clipboard
YYTextView使用autolayout重新计算高度的时候,Text会抖动
忘了贴上代码了
func textViewDidChange(textView: YYTextView) {
let sizeOpt = textView.textLayout?.textBoundingSize
if let size = sizeOpt {
let height = size.height + textView.textContainerInset.top + textView.textContainerInset.bottom + textView.contentInset.top + textView.contentInset.bottom
self.heightConstraint.constant = height > 128 ? height : 128
}
}
等待一个 loop 再执行(比如 dispatch_after(0))。 另外,尽量不要在用户编辑时修改高度。
@ibireme 感谢回复!我试了用 dispatch_after 和 NSTimer ,不管延时多久,换行都有抖动。因为需求原因,文本编辑框下面还有元素,所以需要让文本框在编辑时能根据内容自动伸缩。
我调试了一下。内容高度变化时,contentSize 会改变,内容和光标也会有一个动画移动的效果以保证光标暴露在最外面。这块儿有时间会做一下优化吧。
@heqichang 把字体换成Helvetica可以临时解决这个问题~
@BaeCheung 我试了不行哩,你那换字体解决这问题了?
@ibireme 请问这个问题有答案了吗?我这边也是遇到相同情况。
请问抖动的问题优化了吗?输入时改变文本框尺寸这个功能还是挺常见的。 我现在临时解决的办法是高度比文字高度多一行,在视觉上就看不出来抖动的问题了。
有更好的解决方案么
这样就可以了:
__weak __typeof(self) weakSelf = self;
[self.textView addObserverBlockForKeyPath:@"textLayout.textBoundingSize" block:^(id _Nonnull obj, id _Nullable oldVal, id _Nullable newVal) {
CGFloat height = [[self.textView textLayout] textBoundingSize].height;
weakSelf.textView.height = MIN(kMaxHeight, MAX(50, height));
}];
在这里改就不抖了
-
(BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:newText attributes:textView.attributedText.yy_attributes]; [textView.textParser parseText:str selectedRange:NULL]; YYTextLayout *layout = [YYTextLayout layoutWithContainer:textView.textLayout.container text:str]; CGFloat height = layout.textBoundingSize.height;
}