简体   繁体   中英

How to get content height of UITextView with word wrapping

I am trying to get the content height of an UITextView for calculating the bottom position of it (y position + height). I can get the y position just fine with

travelDescriptionTextView.frame.origin.y

and need to determinate the height. All over the internet it says to get the content height with:

let contentSize = self.travelDescriptionTextView.sizeThatFits(self.travelDescriptionTextView.bounds.size)
let height = contentSize.height

but this technique doesn't work when height is resized (extended) by word wrapping, that is, if a sentence is wider than the width of the text box and the textbox creates a new line automatically. The above technique for getting content height only get the height right if there is no word wrapping, or else the height is excluding the extra word wrapping lines causing the content height to be shorter than the actual content height.

So how do I get the content height of a UITextView containing word wrapping height resizes?

尝试如下,

let textViewComputedHeight = textView.contentSize.height -  textView.contentInset.top - textView.contentInset.bottom

Thanks to RDC for the link. The working solution is:

            self.travelDescriptionTextView.sizeToFit()
            self.travelDescriptionTextView.layoutIfNeeded()
            let contentSize = self.travelDescriptionTextView.sizeThatFits(self.travelDescriptionTextView.bounds.size)
            let textViewHeight = contentSize.height

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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