简体   繁体   English

UITextView不会更新其contentSize

[英]UITextView doesn't update its contentSize

I'm dynamically sizing a UITextView 's height and the height of the UITableViewCell it is embedded in when its content changes. 我正在动态调整UITextView的高度以及内容更改时嵌入的UITableViewCell的高度。 But I also have the ability to paste in predefined bits of texts. 但我也能够粘贴预定义的文本位。

As this pasting happens programmatically, the problem is, that after adding the selected text bit to the UITextView 's text and calling my UITableView to update its cell heights, the UITextView hasn't yet updated its contentSize, which I use to calculate the cell's height. 由于这种粘贴以编程方式发生,问题是,在将所选文本位添加到UITextView的文本并调用我的UITableView来更新其单元格高度后, UITextView尚未更新其contentSize,我用它来计算单元格高度。

Is there a way to force a UITextView to update its contentSize , after I programmatically add text to it? 在我以编程方式向其添加文本后,有没有办法强制UITextView更新其contentSize

You can use sizeThatFits: to get the correct size. 您可以使用sizeThatFits:来获得正确的大小。

CGFloat height = ceilf([textView sizeThatFits:textView.frame.size].height);

Here is a popular open source component that makes use of it to achieve dynamic resizing based on the textview content: https://github.com/HansPinckaers/GrowingTextView 这是一个流行的开源组件,它利用它来实现基于textview内容的动态调整大小: https//github.com/HansPinckaers/GrowingTextView

Swift version of the answer: Swift版的答案:

var newTextViewHeight = ceil(textView.sizeThatFits(textView.frame.size).height)
textView.frame.size.height = newTextViewHeight

This piece of code might also come in handy if you want to update the superview of the UITextView 如果要更新UITextView的超级视图,这段代码也可以派上用场

textView.superview?.frame.size.height = textView.contentSize.height + 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM