简体   繁体   English

获取UITextView的内容高度

[英]Get the content height of a UITextView

I use this open source library called ReadMoreTextView to display a bunch of text. 我使用这个称为ReadMoreTextView的开源库来显示一堆文本。 The library enables me to toggle between displaying an excerpt of the text and showing the full length content (the button is a normal UIButton added by me, not the library). 该库使我可以在显示文本摘录和显示全长内容之间切换(按钮是我添加的普通UIButton,而不是库)。

在此处输入图片说明 在此处输入图片说明

This works as expected. 这按预期工作。

My problem arises when I have to display a smaller amount of text. 当我不得不显示少量文本时,就会出现我的问题。 If I add some content that doesn't exceed the height of the UITextView, I want to hide the more/less toggle button. 如果添加的内容不超过UITextView的高度,则要隐藏更多/更少切换按钮。 So I thought of taking the full content height and if only it's larger than the text view's height, show the toggle button. 因此,我想考虑整个内容的高度,如果仅比文本视图的高度大,请显示切换按钮。

In the above example, I aded a long couple of paragraphs that exceeds the text view bounds. 在上面的示例中,我添加了几段超出文本视图范围的段落。 The text view's height comes up as 128. But the content height also returns 128. There's a library specific method called boundingRectForCharacterRange which is supposed to return the content height also returns a wrong value (100). 文本视图的高度为128。但是内容高度也返回128。有一个特定于库的方法,称为boundingRectForCharacterRange ,应该返回内容高度也返回错误的值(100)。

print("TEXTVIEW HEIGHT: \(textView.bounds.height)") // 128
print("CONTENT HEIGHT: \(textView.contentSize.height)") // 128

let rect = textView.layoutManager.boundingRectForCharacterRange(range: NSRange(location: 0, length: textView.text.count), inTextContainer: textView.textContainer)
print("TEXT HEIGHT: \(rect.height)") // 100

I opened an issue at the library's Github page but the owner asked to ask it here. 我在图书馆的Github页面上打开了一个问题 ,但所有者要求在这里提问。

Why does the content height return a wrong value? 为什么含量高度返回错误的值?

Here is the project I'm using in the above example by the way. 顺便说一下,这是我在以上示例中使用的项目

You can simply use following method to get the content size: 您可以简单地使用以下方法来获取内容大小:

let contentSize = self.textView.sizeThatFits(self.textView.bounds.size)

Then update the textview frame accordingly: 然后相应地更新textview框架:

self.textView.frame = CGRect(width: contentSize.width, height: contentSize.height)

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

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